﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

using Leadtools;
using Leadtools.Codecs;
using Leadtools.WinForms;

using MINERP.BLL.CustomerManage;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using MINERP.COM;
using MINERP.ComControls;
using MINERP.ComControls.Extension;

namespace MINERP.CustomerManage.StartOrder
{
    public partial class FrmEditOrder : FrmParent
    {
        //参数
        private BLL.CustomerManage.StartOrderBLL SOBLL = new MINERP.BLL.CustomerManage.StartOrderBLL();
        int OrderBagID = 0;
        int OrderProductId = 0;
        List<StartOrderBLL.ProductInfo> productListShop;                    //商户特有的产品信息
        List<StartOrderBLL.STProductDisplay> ListProductDisplayShop;        //商户特有的产品显示信息
        List<StartOrderBLL.STProductDisplay> ListProductDisplayUsually;     //常用产品
        List<StartOrderBLL.STProductDisplay> FilterDisplayProduct = new List<StartOrderBLL.STProductDisplay>();     //按类别分类的原始产品信息 
        List<StartOrderBLL.STProductDisplay> SXList = new List<StartOrderBLL.STProductDisplay>();           //助记码筛选的产品集合
        List<StartOrderBLL.STProductDisplay> FilterDisplayProductShop = new List<StartOrderBLL.STProductDisplay>(); //按类别分类的商户产品信息 
        List<StartOrderBLL.STProductDisplay> FilterUsually = new List<StartOrderBLL.STProductDisplay>();            //常用产品分类
        List<StartOrderBLL.ProductInfoEdit> ProductDataSource = new List<StartOrderBLL.ProductInfoEdit>();          //上部显示的产品信息
        List<StartOrderBLL.ProductInfoEdit> ListProduct = new List<StartOrderBLL.ProductInfoEdit>();                //订单的产品集合(经过修改的产品集合)
        List<StartOrderBLL.STPaperType> ListPaperType;  //纸型集合
        List<StartOrderBLL.STPaperFace> ListPaperFace;  //纸面集合
        List<StartOrderBLL.STShop> ListShop;            //商户集合
        List<int> DelProductIDs = new List<int>();      //删除产品的OrderProductId集合,因为只需ID就可以确定产品
        List<int> DelPhotoIDS = new List<int>();        //删除照片的PhotoID集合，因为只需ID就可以确定照片
        bool isAddOldTech = true;                       //是否加载的是原有产品的流程
        MODEL.CustomerManage.CurrentStyleProduct currentStyleProduct = new MINERP.MODEL.CustomerManage.CurrentStyleProduct();   //当前产品的基本样式
        string lastShopName = "";                       //上一个商户的名称

        public List<MODEL.CustomerManage.StartOrder.User> AllUser = new List<MINERP.MODEL.CustomerManage.StartOrder.User>();        //所有的员工(设置节点默认员工使用)
        public List<MODEL.CustomerManage.StartOrder.ShopTechUser> Stu = new List<MINERP.MODEL.CustomerManage.StartOrder.ShopTechUser>();//商户，节点，员工
        public List<MODEL.CustomerManage.StartOrder.ProductOutShop> Po = new List<MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop>();//加载产品所有的委外商
        public int SelectedUserId;                              //选中的员工
        public string SelectedUserName;                         //选中的员工名
        public int SelectedOutShopId = 0;                       //重新选择的委外商
        public string SelectedOutShopName = "";                 //重新选择的委外商名
        private bool ceProductWithoutPhotoClick = false;           //是否鼠标点击  不需要照片的产品类型更改   
        private bool ceProductOutProductClick = false;           //是否鼠标点击  不需要照片的产品类型更改 
        public List<MODEL.CustomerManage.StartOrder.Printer> AllPrinter;        //所有的打印机
        public List<MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO> AllCostItem;//所有收费项目
        List<StartOrderBLL.STProductTech> CommonProductTechBeforePrint = new List<StartOrderBLL.STProductTech>();    //单个产品流程


        //属性
        public FrmManage Manage { get; set; }
        public FtpUpload.FrmCheckAutoOrder CheckAutoOrder { get; set; }
        public int EditUserId { get; set; }             //编辑订单人员
        public int UserType { get; set; }               //调用者类型 1普通的编辑 2自动开单审核
        private static FrmEditOrder _instance;
        public static FrmEditOrder GetInstance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new FrmEditOrder();
                }
                return _instance;
            }
            set
            {
                _instance = null;
            }
        }

        public FrmEditOrder()
        {
            InitializeComponent();
            base.InitiAuthority();

            gvProductList.ShowRowIndicator(50);

            gvProduct.ShowRowIndicator(50);

            //gvUsuallyUse.ShowRowIndicator(50);
            //gvProductCategory.ShowRowIndicator(50);
            //gridView4.ShowRowIndicator(50);
        }
        public FrmEditOrder(int orderBagID, int orderProductId)
        {
            OrderBagID = orderBagID;
            OrderProductId = orderProductId;
            InitializeComponent();
        }

        private void FrmEditOrder_Load(object sender, EventArgs e)
        {
            try
            {
                //测试
                //UserType = 1;   //测试普通的编辑
                //默认显示所有的产品
                //xtraTabControl1.SelectedTabPage = xtraTabPage2;
                //绑定商户下拉列表
                ListShop = SOBLL.GetShopList().OrderBy(p => p.ShopName).ToList();
                foreach (StartOrderBLL.STShop s in ListShop)
                {
                    cbShopName.Properties.Items.Add(s.ShopName);
                }
                //productList = SOBLL.GetProductList();

                /*
                //产品原始信息集合
                productList = SOBLL.GetProductList();
                //产品的显示信息集合
                DisplayProductList = new List<StartOrderBLL.STProductDisplay>();
                foreach (StartOrderBLL.ProductInfo defaltProduct in productList)
                {
                    StartOrderBLL.STProductDisplay display = new StartOrderBLL.STProductDisplay();
                    display.ProductID = defaltProduct.ProductID;
                    display.ProductName = defaltProduct.ProductName;
                    display.ProductCategoryID = defaltProduct.ProductCategoryID;
                    display.ProductCategoryName = defaltProduct.ProductCategoryName;
                    float rh = defaltProduct.Height;
                    float rw = defaltProduct.Width;
                    display.ZJCode = defaltProduct.ZJCode;
                    display.ProductHW = string.Format("{0:0.##}", rh) + "×" + string.Format("{0:0.##}", rw);
                    display.ProductH = rh;
                    display.ProductW = rw;
                    DisplayProductList.Add(display);
                }*/
                //所有产品的流程
                //productTechList = SOBLL.GetProductFlow();       //不应直接加载所有产品的流程,应加载单个产品的流程???????????
               // ListPaperType = new List<StartOrderBLL.STPaperType>();
                ListPaperType = SOBLL.GetPaperType();
                //ListPaperType = SOBLL.GetShopPaperType(this.cbShopName.Text.Trim());
                foreach (StartOrderBLL.STPaperType ptype in ListPaperType)
                {
                    cbPaperType.Properties.Items.Add(ptype.PaperTypeName);
                    repositoryItemComboBoxPaperType.Items.Add(ptype.PaperTypeName);
                }
                //所有纸面
                ListPaperFace = new List<StartOrderBLL.STPaperFace>();
                ListPaperFace = SOBLL.GetPaperFace();
                foreach (StartOrderBLL.STPaperFace pface in ListPaperFace)
                {
                    cbPaperFace.Properties.Items.Add(pface.PaperFaceName);
                    repositoryItemComboBoxPaperFace.Items.Add(pface.PaperFaceName);
                }

                //加载单位
                string unit = Properties.Settings.Default.PreviousUnit;
                cbUnit.Text = unit;
                //上一个使用的单位
                //previousUnit = unit;

                //加载订单包信息
                AddOrderBagInfo();

                //显示照片明细的缩略图容器属性
                browser.Dock = DockStyle.Fill;
                browser.SelectionMode = RasterImageListSelectionMode.Multi;
                browser.KeyDown += new KeyEventHandler(browser_KeyDown);

                //加载所有员工
                AllUser = SOBLL.GetAllUser();
                //加载本商户，节点的默认操作员(在新增产品，修改产品类型时使用)
                foreach (StartOrderBLL.STShop s in ListShop)
                {
                    if (s.ShopName == cbShopName.Text)
                    {
                        Stu = SOBLL.GetShopTechUser(s.ShopID);
                        break;
                    }
                }
                //加载所有打印机
                AllPrinter = SOBLL.GetAllPrinter();
                BindPrinter();
                CommonProductTechBeforePrint = SOBLL.GetAllFlowTechBeforPrint();


                //所有纸型
                ListPaperType = new List<StartOrderBLL.STPaperType>();
                //ListPaperType = SOBLL.GetPaperType();
                ListPaperType = SOBLL.GetShopPaperType(this.cbShopName.Text.Trim());
                cbPaperType.Properties.Items.Clear();
                repositoryItemComboBoxPaperType.Items.Clear();
                foreach (StartOrderBLL.STPaperType ptype in ListPaperType)
                {
                    cbPaperType.Properties.Items.Add(ptype.PaperTypeName);
                    repositoryItemComboBoxPaperType.Items.Add(ptype.PaperTypeName);
                }
              
                //取到所有的收费项目
                //AllCostItem = SOBLL.GetAllCostItems(cbShopName.Text.Trim());
                AllCostItem = SOBLL.GetShopCostItems(cbShopName.Text.Trim());
                foreach (MINERP.MODEL.CustomerManage.StartOrder.CommonChargeItemDDO ddo in AllCostItem)
                {
                    repositoryItemCheckedComboBoxEditCostType.Items.Add(ddo.ItemName);
                }
                //cbShopName.SelectedItem
                string shopName = this.cbShopName.Text;

                productListShop = SOBLL.GetShopProductList(ListShop.FirstOrDefault(p => p.ShopName == shopName).ShopID);

                ListProductDisplayShop = new List<StartOrderBLL.STProductDisplay>();
                gcProductTemplate.DataSource = productListShop;
                gcProductTemplate.RefreshDataSource();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #region 设置商户特有的产品分组
        /// <summary>
        /// 设置商户特有的产品分组
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbShopName_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string sname = cbShopName.Text;
                if (lastShopName == sname)
                    return;
                lastShopName = sname;
               // xtraTabControl1.SelectedTabPage = xtraTabPage1;
                //获取商户特有的产品集合
                string shopName = cbShopName.Text;
                int shopId = 0;
                foreach (StartOrderBLL.STShop s in ListShop)
                {
                    if (s.ShopName == shopName)
                    {
                        shopId = s.ShopID;
                        break;
                    }
                }

                ////移除对Grid的引用
                //foreach (DevExpress.XtraNavBar.NavBarGroup g in bcProductCommon.Groups)
                //{
                //    if (g.ControlContainer != null && g.ControlContainer.Controls.Contains(gcProductCategoryShop))
                //    {
                //        g.ControlContainer.Controls.Remove(gcProductCategoryShop);
                //        break;
                //    }
                //}
                //bcProductCommon.Groups.Clear();
                //ListProductDisplayUsually = null;
                //if (shopId == 0)
                //    return;
                //productListShop = SOBLL.GetShopProductList(shopId);

                //ListProductDisplayShop = new List<StartOrderBLL.STProductDisplay>();
                //foreach (StartOrderBLL.ProductInfo s in productListShop)
                //{
                //    StartOrderBLL.STProductDisplay display = new StartOrderBLL.STProductDisplay();
                //    display.ProductID = s.ProductID;
                //    display.ProductName = s.ProductName;
                //    display.ProductCategoryID = s.ProductCategoryID;
                //    display.ProductCategoryName = s.ProductCategoryName;
                //    float rh = s.Height;
                //    float rw = s.Width;
                //    display.ProductHW = string.Format("{0:0.##}", rh) + "×" + string.Format("{0:0.##}", rw);
                //    display.ProductH = rh;
                //    display.ProductW = rw;
                //    display.ZJCode = s.ZJCode;
                //    display.UsedTimes = s.UsedTimes;
                //    ListProductDisplayShop.Add(display);
                //}

                //var groups = ListProductDisplayShop.GroupBy(p => p.ProductCategoryID);


                //foreach (var group in groups)
                //{
                //    foreach (var item in group)
                //    {
                //        DevExpress.XtraNavBar.NavBarGroup g = new DevExpress.XtraNavBar.NavBarGroup();
                //        g.Caption = item.ProductCategoryName;
                //        g.Tag = item.ProductCategoryID;
                //        bcProductCommon.Groups.Add(g);
                //        break;
                //    }
                //}
                //if (bcProductCommon.Groups != null && bcProductCommon.Groups.Count == 1)
                //{
                //    DevExpress.XtraNavBar.NavBarGroup group = new DevExpress.XtraNavBar.NavBarGroup();
                //    group.Caption = "";
                //    group.Expanded = false;
                //    bcProductCommon.Groups.Add(group);
                //}
                //xtraTabControl1.SelectedTabPage = xtraTabPage3;

                //设置商户对应的节点操作员
                if (!Stu.Exists(p => p.ShopId == shopId))            //商户，节点，操作员是否已加载
                {
                    Stu.AddRange(SOBLL.GetShopTechUser(shopId));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }


        
        #endregion

        #region 绑定打印机
        /// <summary>
        /// 绑定打印机
        /// </summary>
        private void BindPrinter()
        {
            try
            {
                cbPrinter.DisplayMember = "PrinterName";
                cbPrinter.ValueMember = "PrinterId";
                cbPrinter.DataSource = AllPrinter;
                cbPrinter.SelectedValue = 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 设置时间
        /// <summary>
        /// 设置时间
        /// </summary>
        private void SetTime()
        {
            dtOrderTime.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分");
            dtPreCompleteTime.Text = DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分");
        }
        #endregion

        #region 单击关闭时间编辑器
        private void dtOrderTime_Properties_VistaTimeProperties_EditValueChanged(object sender, EventArgs e)
        {
            //dtOrderTime.ClosePopup();
        }

        private void dtPreCompleteTime_Properties_VistaTimeProperties_EditValueChanged(object sender, EventArgs e)
        {
            //dtPreCompleteTime.ClosePopup();
        }
        #endregion

        #region 选择产品的操作

        #region 加载订单包信息
        private void AddOrderBagInfo()
        {
            try
            {
                //如果订单包内还有照片没移完，商户不能改
                bool photoMoveCompleted = SOBLL.PhotoMoveCompleted(OrderBagID);
                if (!photoMoveCompleted)
                {
                    cbShopName.Enabled = false;
                }
                //加载订单包信息
                ProductDataSource = SOBLL.GetOrderInfoByOrderID(OrderBagID);        //ProductDataSource 上部显示的产品信息
                gcProductList.DataSource = ProductDataSource;
                gcProductList.RefreshDataSource();
                SetOrderInfoFoced();                //设置修改的产品获得焦点
                SetOrderTitle();                    //设置订单头信息
                AddProductsInOrderBag();            //设置该订单包内所有产品的纸型、纸面
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //当前产品获得焦点
        private void SetOrderInfoFoced()
        {
            if (OrderProductId != 0)
            {
                for (int i = 0; i < gvProductList.RowCount; i++)
                {
                    StartOrderBLL.ProductInfoEdit p = gvProductList.GetRow(i) as StartOrderBLL.ProductInfoEdit;
                    if (p.OrderProductId == OrderProductId)
                    {
                        gvProductList.FocusedRowHandle = i;
                        break;
                    }
                }
            }
        }
        #endregion

        #region 添加产品列表
        /// <summary>
        /// 添加产品列表
        /// </summary>
        /*private void AddProduct()
        {
            bcProduct.Groups.Clear();
            foreach (StartOrderBLL.STProduct product in productList)
            {
                int productID = product.ProductID;
                int productCategoryID = product.ProductCategoryID;
                bool IsExistGroup = false;
                foreach (DevExpress.XtraNavBar.NavBarGroup g in bcProduct.Groups)
                {
                    if (Convert.ToInt16(g.Tag) == productCategoryID)
                    {
                        IsExistGroup = true;    //表示组已存在
                        //向组内添加元素
                        AddItemToProductGroup(product, g);
                        break;
                    }
                }
                if (IsExistGroup == false)  //如果组不存在，就添加
                {
                    DevExpress.XtraNavBar.NavBarGroup group = new DevExpress.XtraNavBar.NavBarGroup();
                    group.Caption = product.ProductCategoryName;
                    group.Tag = productCategoryID;
                    group.Expanded = false;
                    AddItemToProductGroup(product, group);
                    bcProduct.Groups.Add(group);
                }

            }
        }*/
        private void AddProduct(List<StartOrderBLL.STProductDisplay> srcList)
        {
            //移除对Grid的引用
            
            //foreach (StartOrderBLL.STProductDisplay product in srcList)
            //{
            //    int productID = product.ProductID;
            //    int productCategoryID = product.ProductCategoryID;
            //    bool IsExistGroup = false;
            //    foreach (DevExpress.XtraNavBar.NavBarGroup g in bcProduct.Groups)
            //    {
            //        if (Convert.ToInt16(g.Tag) == productCategoryID)
            //        {
            //            IsExistGroup = true;    //表示组已存在
            //            break;
            //        }
            //    }
            //    if (IsExistGroup == false)  //如果组不存在，就添加
            //    {
            //        DevExpress.XtraNavBar.NavBarGroup group = new DevExpress.XtraNavBar.NavBarGroup();
            //        group.Caption = product.ProductCategoryName;
            //        group.Tag = productCategoryID;
            //        group.Expanded = false;
            //        bcProduct.Groups.Add(group);
            //    }
            //}
            //if (bcProduct.Groups != null && bcProduct.Groups.Count == 1)
            //{
            //    DevExpress.XtraNavBar.NavBarGroup group = new DevExpress.XtraNavBar.NavBarGroup();
            //    group.Caption = "";
            //    group.Expanded = false;
            //    bcProduct.Groups.Add(group);
            //}
            //productListShop.Where(p=>p.ZJCode)

        }
        #endregion 添加产品列表

        #region 向产品列表组内添加产品
        /// <summary>
        /// 向产品列表组内添加产品
        /// </summary>
        /*
        private void AddItemToProductGroup(StartOrderBLL.STProduc product, DevExpress.XtraNavBar.NavBarGroup group)
        {
            string itemStr = product.ProductName + "(" + product.Height.ToString() + "×" + product.Width.ToString() + ")" + product.PageNum.ToString();
            DevExpress.XtraNavBar.NavBarItem item = new DevExpress.XtraNavBar.NavBarItem(itemStr);
            item.Tag = product.ProductID;
            group.ItemLinks.Add(item);
        }*/
        #endregion

        #region 展开某类产品时，其他类型的产品都关闭
        //
        
        //以导航模式展开的触发事件
        //private void bcProduct_ActiveGroupChanged(object sender, DevExpress.XtraNavBar.NavBarGroupEventArgs e)
        //{
        //    try
        //    {
        //        e.Group.GroupStyle = DevExpress.XtraNavBar.NavBarGroupStyle.ControlContainer;
        //        DevExpress.XtraGrid.GridControl grid = gcProductCategory;
        //        grid.Visible = true;
        //        FilterDisplayProduct.Clear();       //清除上一类别的信息
        //        int productCategoryID = Convert.ToInt16(e.Group.Tag);
        //        foreach (StartOrderBLL.STProductDisplay product in ListProductDisplayShop)
        //        {
        //            if (product.ProductCategoryID == productCategoryID)
        //            {
        //                FilterDisplayProduct.Add(product);
        //            }
        //        }
        //        grid.DataSource = FilterDisplayProduct;
        //        grid.RefreshDataSource();
        //        grid.Dock = DockStyle.Fill;
        //        e.Group.ControlContainer.Controls.Add(grid);
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //    }
        //}
        ////展开商户特有的产品
        //private void bcProductCommon_ActiveGroupChanged(object sender, DevExpress.XtraNavBar.NavBarGroupEventArgs e)
        //{
        //    try
        //    {
        //        e.Group.GroupStyle = DevExpress.XtraNavBar.NavBarGroupStyle.ControlContainer;
        //        DevExpress.XtraGrid.GridControl grid = gcProductCategoryShop;
        //        grid.Visible = true;
        //        FilterDisplayProductShop.Clear();
        //        int productCategoryID = Convert.ToInt16(e.Group.Tag);
        //        foreach (StartOrderBLL.STProductDisplay product in ListProductDisplayShop)
        //        {
        //            if (product.ProductCategoryID == productCategoryID)
        //            {
        //                FilterDisplayProductShop.Add(product);
        //            }
        //        }
        //        //grid = new DevExpress.XtraGrid.GridControl();
        //        ////grid.isd
        //        grid.DataSource = FilterDisplayProductShop;
        //        grid.RefreshDataSource();
        //        grid.Dock = DockStyle.Fill;
        //        e.Group.ControlContainer.Controls.Add(grid);
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //    }
        //}
        ////常用产品
        //private void bcUsuallyUse_ActiveGroupChanged(object sender, DevExpress.XtraNavBar.NavBarGroupEventArgs e)
        //{
        //    try
        //    {
        //        e.Group.GroupStyle = DevExpress.XtraNavBar.NavBarGroupStyle.ControlContainer;
        //        gcUsuallyUse.Visible = true;
        //        FilterUsually.Clear();
        //        int categoryId = Convert.ToInt32(e.Group.Tag);
        //        foreach (StartOrderBLL.STProductDisplay p in ListProductDisplayUsually)
        //        {
        //            if (p.ProductCategoryID == categoryId)
        //                FilterUsually.Add(p);
        //        }
        //        gcUsuallyUse.Dock = DockStyle.Fill;
        //        e.Group.ControlContainer.Controls.Add(gcUsuallyUse);
        //        gcUsuallyUse.DataSource = FilterUsually;
        //        gcUsuallyUse.RefreshDataSource();
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //    }
        //}
        #endregion

        #endregion

        #region 产品开始拖曳
        private void bcProduct_LinkPressed(object sender, DevExpress.XtraNavBar.NavBarLinkEventArgs e)
        {
            string xx = e.Link.Item.Tag.ToString();
            DataObject data = new DataObject();
            data.SetData(DataFormats.StringFormat, xx);
            DoDragDrop(data, DragDropEffects.All);
        }
        //gridControls拖曳
        GridHitInfo downHitInfo = null;
        private void gvProductCategory_MouseDown(object sender, MouseEventArgs e)
        {
            GridView view = sender as GridView;
            GridHitInfo hitInfo = view.CalcHitInfo(e.X, e.Y);
            if (Control.ModifierKeys != Keys.None) return;
            if (e.Button == MouseButtons.Left && hitInfo.InRow && hitInfo.HitTest != GridHitTest.RowIndicator)
                downHitInfo = hitInfo;

        }

        private void gvProductCategory_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (e.Button == MouseButtons.Left && downHitInfo != null)
                {
                    Size dragSize = SystemInformation.DragSize;
                    Rectangle dragRect = new Rectangle(new Point(downHitInfo.HitPoint.X - dragSize.Width / 2,
                        downHitInfo.HitPoint.Y - dragSize.Height / 2), dragSize);
                    if (!dragRect.Contains(new Point(e.X, e.Y)))
                    {
                        int[] rows = view.GetSelectedRows();

                        if (rows.Length > 0)
                        {
                            if (!view.IsGroupRow(rows[0]))
                            {
                                StartOrderBLL.STProductDisplay product = (StartOrderBLL.STProductDisplay)view.GetRow(rows[0]);
                                int pid = product.ProductID;
                                DataObject data = new DataObject();
                                data.SetData(DataFormats.StringFormat, pid.ToString());
                                DoDragDrop(data, DragDropEffects.All);
                                downHitInfo = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }


        private void gvUsuallyUse_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                downHitInfo = null;
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.X, e.Y);
                if (ModifierKeys != Keys.None) return;
                if (e.Button == MouseButtons.Left && hitInfo.InRow && hitInfo.HitTest != GridHitTest.RowIndicator)
                    downHitInfo = hitInfo;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void gvUsuallyUse_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (e.Button == MouseButtons.Left && downHitInfo != null)
                {
                    System.Drawing.Size dragSize = SystemInformation.DragSize;
                    Rectangle rec = new Rectangle(new Point(downHitInfo.HitPoint.X - dragSize.Width / 2, downHitInfo.HitPoint.Y - dragSize.Height / 2), dragSize);
                    if (!rec.Contains(e.X, e.Y))
                    {
                        int[] rows = view.GetSelectedRows();

                        if (rows.Length > 0)
                        {
                            if (!view.IsGroupRow(rows[0]))
                            {
                                //DragType = 3;                                               //产品模板
                                StartOrderBLL.STProductDisplay product = (StartOrderBLL.STProductDisplay)view.GetRow(rows[0]);
                                int pid = product.ProductID;
                                DataObject data = new DataObject();
                                data.SetData(DataFormats.StringFormat, pid.ToString());
                                DoDragDrop(data, DragDropEffects.All);
                                downHitInfo = null;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 设置订单头信息
        /// <summary>
        /// 设置订单头信息
        /// </summary>
        private void SetOrderTitle()
        {
            try
            {
                StartOrderBLL.STOrderBagTitle orderTitle = SOBLL.GetOrderBagTitle(OrderBagID);
                txtOrderBagCode.Text = orderTitle.OrderBagCode;
                txtOrderName.Text = orderTitle.OrderName;
                cbPriority.Text = orderTitle.OrderPriority.ToString();
                cbShopName.Text = orderTitle.ShopName;
                dtOrderTime.Text = orderTitle.OrderTime.ToString("yyyy年MM月dd日 HH时mm分");
                dtPreCompleteTime.Text = orderTitle.PreCompleteTime.ToString("yyyy年MM月dd日 HH时mm分");
                txtShopRequire.Text = orderTitle.OrderRemark;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 加载一个订单包内的产品
        /// <summary>
        /// 加载一个订单包内的产品
        /// </summary>
        private void AddProductsInOrderBag()
        {
            try
            {
               
                //获取纸型、纸面名称
                foreach (StartOrderBLL.ProductInfoEdit p in ProductDataSource)
                {
                    foreach (StartOrderBLL.STPaperType paperType in ListPaperType)
                    {
                        if (p.PaperTypeID == paperType.PaperTypeID)
                        {
                            p.PaperTypeName = paperType.PaperTypeName;
                            break;
                        }
                    }
                    foreach (StartOrderBLL.STPaperFace paperFace in ListPaperFace)
                    {
                        if (p.PaperFaceID == paperFace.PaperFaceID)
                        {
                            p.PaperFaceName = paperFace.PaperFaceName;
                            break;
                        }
                    }
                }
                gcProductList.RefreshDataSource();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region "产品删除"按钮
        //"产品删除"
        private void tsDeleteProduct_Click(object sender, EventArgs e)
        {
            try
            {
                if (ProductDataSource == null || gvProductList.SelectedRowsCount == 0)
                    return;
                //客户名称不可用
                txtCtmName.Enabled = false;
                int delIndex = gvProductList.GetSelectedRows()[0];
                StartOrderBLL.ProductInfoEdit tproduct = gvProductList.GetRow(delIndex) as StartOrderBLL.ProductInfoEdit;
                int orderProductID = tproduct.OrderProductId;
                int productSerialID = tproduct.ProductSerialID;
                if (orderProductID != 0)                                                    //删除原有产品
                {
                    DeleteProductOldProduct(orderProductID);
                }
                else                                                                        //删除新增产品
                {
                    DeleteProductNewProduct(productSerialID);
                }
                gcProductList.RefreshDataSource();
                ClearProductDetail();                                                       //清空记录
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region Del键删除
        //Del键删除
        private void gvProductList_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (ListProduct == null || gvProductList.SelectedRowsCount == 0)
                    return;
                if (e.KeyData == Keys.Delete)
                {
                    int delIndex = gvProductList.GetSelectedRows()[0];

                    int orderProductID = ProductDataSource[delIndex].OrderProductId;
                    int productSerialID = ProductDataSource[delIndex].ProductSerialID;
                    if (orderProductID != 0)                                                //删除原有产品
                    {
                        DeleteProductOldProduct(orderProductID);
                    }
                    else                                                                    //删除新增产品
                    {
                        DeleteProductNewProduct(productSerialID);
                    }
                    gcProductList.RefreshDataSource();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 删除产品的操作
        /// <summary>
        /// 删除产品的操作 (按原有产品的orderProductID)
        /// </summary>
        /// <param name="orderProductId"></param>
        private void DeleteProductOldProduct(int orderProductId)
        {
            try
            {
                if (DialogResult.Yes == MessageBox.Show("确定要删除吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                {
                    foreach (StartOrderBLL.ProductInfoEdit product in ProductDataSource)
                    {
                        if (product.OrderProductId == orderProductId)
                        {
                            DelProductIDs.Add(product.OrderProductId);                      //删除产品的OrderProductId集合，保存起来用于更新数据库
                            ProductDataSource.Remove(product);
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 删除产品的操作 (按新增产品的SerialID)
        /// </summary>
        /// <param name="productSerialID"></param>
        private void DeleteProductNewProduct(int productSerialID)
        {
            try
            {
                if (DialogResult.Yes == MessageBox.Show("确定要删除吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                {
                    foreach (StartOrderBLL.ProductInfoEdit product in ProductDataSource)
                    {
                        if (product.ProductSerialID == productSerialID)
                        {
                            ProductDataSource.Remove(product);
                            ListProduct.Remove(product);
                            isNewProductCreating = false;                                   //表示删除后，当前不存在正在操作新增产品
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 单击产品
        //单击产品
        private void gvProductList_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Left && e.Clicks == 1)
                {
                    this.Cursor = Cursors.WaitCursor;
                    if (isNewProductCreating == true)                                   //是否正在创建新产品(若新产品正在创建，其他操作不可用)
                    {
                        Cursor = Cursors.Default;
                        MessageBox.Show("请先设置新增产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    if (IsModifyProductType == true)
                    {
                        Cursor = Cursors.Default;
                        MessageBox.Show("请先设置要修改类型的产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    if ((int)COM.OrderInfoStatus.Stop == Convert.ToInt16(gvProductList.GetRowCellValue(e.RowHandle, "Status")))
                    {
                        Cursor = Cursors.Default;
                        MessageBox.Show("暂停的产品不能编辑!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    // int iii = ListProduct.Count;
                    ModifyProductCommon();                      //修改产品的公告操作
                    Cursor = Cursors.Default;
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion



        public void ModifyProductCommon()
        {
            try
            {
                isAddOldTech = true;                                                //表示加载的是已有产品的流程
                isExistsEditProduct = true;                                         //表示当前存在正被编辑的产品
                if (DisplayMode == true)
                {
                    //移除缩略图对象,加载列表对象
                    spcProductDetail.Panel2.Controls.Clear();
                    spcProductDetail.Panel2.Controls.Add(gcProduct);
                    DisplayMode = false;
                }
                //清除表示当前产品照片变化的三个集合,及当前显示的产品照片集合
                currentPhotos.Clear();                                              //当前显示使用的照片集合
                NewPhotos.Clear();
                ModifyPhotos.Clear();
                DelPhotos.Clear();

                int[] indexes = gvProductList.GetSelectedRows();
                if (indexes.Length > 0)
                {
                    StartOrderBLL.ProductInfoEdit tproduct = gvProductList.GetRow(indexes[0]) as StartOrderBLL.ProductInfoEdit;
                    int OrderProductId = tproduct.OrderProductId;//ProductDataSource[indexes[0]].OrderProductId;
                    currentProductID = OrderProductId;
                    int productSerialID = tproduct.ProductSerialID;
                    currentProductSerialID = productSerialID;                           //OrderProductId==0时,productSerialID标识新增产品
                    bool isExist = false;
                    if (OrderProductId == 0)                                            //表示是新增产品
                    {
                        foreach (StartOrderBLL.ProductInfoEdit product in ListProduct)
                        {
                            if (product.ProductSerialID == productSerialID)
                            {
                                isExist = true;
                                //原先已加载过，直接从内存加载
                                browser.Items.Clear();
                                PhotoAndThumbList.Clear();
                                currentPhotos.Clear();                                  //上一个产品的照片显示集合
                                //if (CurrentProductTypeCode)
                                CurrentProductTypeCode = tproduct.ProductTypeCode;


                                //当前产品的基本样式
                                //产品尺寸如果产品时需要设计的产品就重新指定尺寸
                                if (currentStyleProduct.ProductTypeCode!=(int)OrderInfoProductType.NoPhotoProduct)
                                {
                                    currentStyleProduct.ProductTypeCode = tproduct.ProductTypeCode;
                                }
                                

                                if (!tproduct.IsCheckStyle)
                                {
                                    if (tproduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignPrint || tproduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignProduct)
                                    {
                                        FrmCheckSizeAndPageEdit frm = new FrmCheckSizeAndPageEdit(tproduct);
                                        frm.SizeUnit = "英寸(in)";
                                        frm.Width = tproduct.Width;
                                        frm.Height = tproduct.Height;
                                        if (DialogResult.OK == frm.ShowDialog())
                                        {
                                            string unit = frm.SizeUnit;
                                            double height = frm.Height;
                                            double width = frm.Width;
                                            switch (unit)
                                            {
                                                case "厘米(cm)":
                                                    currentStyleProduct.ProductHeight = height / (float)2.54;
                                                    currentStyleProduct.ProductWidth = width / (float)2.54;
                                                    break;
                                                case "英寸(in)":
                                                    currentStyleProduct.ProductHeight = height;
                                                    currentStyleProduct.ProductWidth = width;
                                                    break;
                                                case "米(m)":
                                                    currentStyleProduct.ProductHeight = height * 100 / (float)2.54;
                                                    currentStyleProduct.ProductWidth = width * 100 / (float)2.54;
                                                    break;
                                                case "毫米(mm)":
                                                    currentStyleProduct.ProductHeight = height / 100 / (float)2.54;
                                                    currentStyleProduct.ProductWidth = width / 100 / (float)2.54;
                                                    break;
                                            }

                                        }
                                        else
                                        {
                                            currentStyleProduct.ProductHeight = tproduct.Height;
                                            currentStyleProduct.ProductWidth = tproduct.Width;
                                        }
                                    }
                                    else
                                    {
                                        currentStyleProduct.ProductHeight = tproduct.Height;
                                        currentStyleProduct.ProductWidth = tproduct.Width;
                                    }
                                }

                                currentStyleProduct.MaxHeight = currentStyleProduct.ProductHeight * 1.1;
                                currentStyleProduct.MinHeight = currentStyleProduct.ProductHeight * 0.9;
                                currentStyleProduct.MaxWidth = currentStyleProduct.ProductWidth * 2 * 1.1;
                                currentStyleProduct.MinWidth = currentStyleProduct.ProductWidth * 2 * 0.9;
                                SetPhotoAndThumbList(product.Photos);                   //设置大对象(因为大对象显示当前产品，因此每次加载产品都需更新)
                                DisPlayProductInfo(tproduct);
                            }
                        }
                    }
                    else                                                                //表示是原有产品
                    {
                        foreach (StartOrderBLL.ProductInfoEdit product in ListProduct)
                        {
                            if (product.OrderProductId == OrderProductId)
                            {
                                isExist = true;
                                //原先已加载过，直接从内存加载                          //清除上一个产品内的照片集合
                                browser.Items.Clear();
                                PhotoAndThumbList.Clear();
                                currentPhotos.Clear();
                                CurrentProductTypeCode = tproduct.ProductTypeCode;                            //上一个产品的照片显示集合
                                #region//设计产品规定尺寸
                                if (!tproduct.IsCheckStyle)
                                {
                                    if (tproduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignPrint || tproduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignProduct)
                                    {
                                        FrmCheckSizeAndPageEdit frm = new FrmCheckSizeAndPageEdit(tproduct);
                                        frm.SizeUnit = "英寸(in)";
                                        frm.Width = tproduct.Width;
                                        frm.Height = tproduct.Height;
                                        if (DialogResult.OK == frm.ShowDialog())
                                        {
                                            string unit = frm.SizeUnit;
                                            double height = frm.Height;
                                            double width = frm.Width;
                                            tproduct.IsCheckStyle = true;
                                            switch (unit)
                                            {
                                                case "厘米(cm)":
                                                    currentStyleProduct.ProductHeight = height / (float)2.54;
                                                    currentStyleProduct.ProductWidth = width / (float)2.54;
                                                    break;
                                                case "英寸(in)":
                                                    currentStyleProduct.ProductHeight = height;
                                                    currentStyleProduct.ProductWidth = width;
                                                    break;
                                                case "米(m)":
                                                    currentStyleProduct.ProductHeight = height * 100 / (float)2.54;
                                                    currentStyleProduct.ProductWidth = width * 100 / (float)2.54;
                                                    break;
                                                case "毫米(mm)":
                                                    currentStyleProduct.ProductHeight = height / 100 / (float)2.54;
                                                    currentStyleProduct.ProductWidth = width / 100 / (float)2.54;
                                                    break;
                                            }

                                        }
                                        else
                                        {
                                            currentStyleProduct.ProductHeight = tproduct.Height;
                                            currentStyleProduct.ProductWidth = tproduct.Width;
                                            tproduct.IsCheckStyle = false;
                                        }
                                    }
                                    else
                                    {
                                        currentStyleProduct.ProductHeight = tproduct.Height;
                                        currentStyleProduct.ProductWidth = tproduct.Width;
                                    }
                                }
                                
                                #endregion

                                if (IsModifyProductType == true)
                                {
                                    //加载流程
                                    AddPrductTechs(product);
                                }
                                //当前产品的基本样式
                                currentStyleProduct.ProductTypeCode = tproduct.ProductTypeCode;

                                 #region//设计产品规定尺寸
                                if (!tproduct.IsCheckStyle)
                                {
                                    if (tproduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignPrint || tproduct.ProductTypeCode == (int)OrderInfoProductType.NeedDesignProduct)
                                    {
                                        FrmCheckSizeAndPageEdit frm = new FrmCheckSizeAndPageEdit(tproduct);
                                        frm.SizeUnit = "英寸(in)";
                                        frm.Width = tproduct.Width;
                                        frm.Height = tproduct.Height;
                                        if (DialogResult.OK == frm.ShowDialog())
                                        {
                                            string unit = frm.SizeUnit;
                                            double height = frm.Height;
                                            double width = frm.Width;
                                            tproduct.IsCheckStyle = true;
                                            switch (unit)
                                            {
                                                case "厘米(cm)":
                                                    currentStyleProduct.ProductHeight = height / (float)2.54;
                                                    currentStyleProduct.ProductWidth = width / (float)2.54;
                                                    break;
                                                case "英寸(in)":
                                                    currentStyleProduct.ProductHeight = height;
                                                    currentStyleProduct.ProductWidth = width;
                                                    break;
                                                case "米(m)":
                                                    currentStyleProduct.ProductHeight = height * 100 / (float)2.54;
                                                    currentStyleProduct.ProductWidth = width * 100 / (float)2.54;
                                                    break;
                                                case "毫米(mm)":
                                                    currentStyleProduct.ProductHeight = height / 100 / (float)2.54;
                                                    currentStyleProduct.ProductWidth = width / 100 / (float)2.54;
                                                    break;
                                            }

                                        }
                                        else
                                        {
                                            currentStyleProduct.ProductHeight = tproduct.Height;
                                            currentStyleProduct.ProductWidth = tproduct.Width;
                                        }
                                    }
                                    else
                                    {
                                        currentStyleProduct.ProductHeight = tproduct.Height;
                                        currentStyleProduct.ProductWidth = tproduct.Width;
                                    }
                                }
                                #endregion
                                currentStyleProduct.ProductHeight = tproduct.Height;
                                currentStyleProduct.ProductWidth = tproduct.Width;
                                currentStyleProduct.MaxHeight = currentStyleProduct.ProductHeight * 1.1;
                                currentStyleProduct.MinHeight = currentStyleProduct.ProductHeight * 0.9;
                                currentStyleProduct.MaxWidth = currentStyleProduct.ProductWidth * 2 * 1.1;
                                currentStyleProduct.MinWidth = currentStyleProduct.ProductWidth * 2 * 0.9;
                                SetPhotoAndThumbList(product.Photos);                   //设置大对象 
                                DisPlayProductInfo(tproduct);
                            }
                        }
                    }
                    if (isExist == false)                                               //产品的照片信息还未加载进内存
                    {
                        //加载原有的产品头信息与照片信息进内存
                        browser.Items.Clear();
                        currentPhotos.Clear();
                        CurrentProductTypeCode = tproduct.ProductTypeCode;
                        AddProductIntoMemery(tproduct);
                        PhotoAndThumbList.Clear();                                        //上一个产品的照片显示集合
                        SetPhotoAndThumbList(tproduct.Photos);     //设置大对象
                        DisPlayProductInfo(tproduct);              //显示产品内部信息
                        ListProduct.Add(tproduct);                 //将产品添加进产品修改集合(该集合用于保存进数据库)???为什么只有这里加入??????
                    }

                    SetPhotoNumAndArea(tproduct.ProductTypeCode); //设置照片数量和总面积
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region 新增产品还未设置明细时，其他产品不可操作
        private void gvProductList_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo hitInfo = gvProductList.CalcHitInfo(new Point(e.X, e.Y));
                if (hitInfo.InRow && isNewProductCreating == true)
                {
                    for (int i = 0; i < gvProductList.RowCount; i++)
                    {
                        StartOrderBLL.ProductInfo product = gvProductList.GetRow(i) as StartOrderBLL.ProductInfo;
                        if (product.ProductSerialID == currentProductSerialID)
                        {
                            gvProductList.FocusedRowHandle = i;
                            if (hitInfo.RowHandle != i)
                            {
                                MessageBox.Show("请先设置新增产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 照片列表头部,单位变化，显示随着变化
        /// <summary>
        /// 照片列表头部,单位变化，显示随着变化
        /// </summary>
        private void DisplayByUnit(string unit)
        {
            string disUnit = "";
            string disUnitArea = "";
            switch (unit)
            {
                case "厘米(cm)":
                    disUnit = "高×宽(厘米)";
                    disUnitArea = "面积(平方厘米)"; break;
                case "英寸(in)":
                    disUnit = "高×宽(英寸)";
                    disUnitArea = "面积(平方英寸)"; break;
                case "米(m)":
                    disUnit = "高×宽(米)";
                    disUnitArea = "面积(平方米)"; break;
                case "毫米(mm)":
                    disUnit = "高×宽(毫米)";
                    disUnitArea = "面积(平方毫米)"; break;
            }
            gvProduct.Columns["PhotoHW"].Caption = disUnit;
            gvProduct.Columns["PhotoArea"].Caption = disUnitArea;
        }
        #endregion

        #region 设置照片数量与面积
        /// <summary>
        /// 设置照片数量与面积
        /// </summary>
        /// <param name="photo">产品</param>
        private void SetPhotoNumAndArea(int productTypeCode)                       //产品是扩印还是非扩印
        {
            try
            {
                if (currentPhotos != null && currentPhotos.Count != 0)
                {
                    int photoNum = 0;
                    float h = (float)Convert.ToDouble(spinHeight.Tag);
                    float w = (float)Convert.ToDouble(spinWidth.Tag);
                    int productNum = Convert.ToInt16(spinProductNum.Text.Trim());           //产品份数                      
                    float areaStandard = 0;                                                 //标准面积
                    float area = 0;
                    if (gcProduct.DataSource != null)                                       //表示当前无产品
                    {
                        if (productTypeCode == (int)OrderInfoProductType.NeedDesignPrint || productTypeCode == (int)OrderInfoProductType.NeedDesignProduct)             //实质是ProductTypeCode。按产品的尺寸计算总面积
                        {
                            int pageNum = Convert.ToInt16(spinPageNum.Text.Trim());         //Page数
                            areaStandard = h * w * pageNum * productNum;

                        }
                        else                                                                //按照片本身的面积计算总面积
                        {
                            //冲印产品的设置
                            foreach (StartOrderBLL.STPhotoEdit photo in currentPhotos)
                            {
                                areaStandard += (float)Convert.ToDouble(photo.PhotoAreaStandard);
                            }
                            areaStandard *= productNum;
                        }
                        photoNum = currentPhotos.Count;
                    }
                    switch (cbUnit.Text.Trim())
                    {
                        case "厘米(cm)":
                            area = (float)(areaStandard * 2.54 * 2.54); break;
                        case "英寸(in)":
                            area = areaStandard; break;
                        case "米(m)":
                            area = (float)(areaStandard * 2.54 * 2.54 * 0.01 * 0.01); break;
                        case "毫米(mm)":
                            area = (float)(areaStandard * 2.54 * 2.54 * 10 * 10); break;
                    }
                    lblPhotoNum.Text = photoNum.ToString();
                    lblProductArea.Text = string.Format("{0:0.####}", area);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        //--------------------------------------------------------------
        //------------------------产品内部的操作------------------------
        //--------------------------------------------------------------
        //List<StartOrderBLL.STPhotoEdit> PhotoDataSource;            //产品照片的数据源
        List<PhotoListAndThumb> PhotoAndThumbList = new List<PhotoListAndThumb>();    //产品的大对象集合(保存当前产品内的照片)
        RasterThumbnailBrowser browser = new RasterThumbnailBrowser();              //缩略图容器
        List<string> ListAllPhotoPath = new List<string>();         //每次添加照片时，所有的照片路径集合
        //StartOrderBLL.ProductInfoEdit currentProduct;               //当前正在操作的产品
        int currentProductID;                                       //标识原有产品的ID
        int currentNewProductId;                                    //修改的产品ID
        int ProductSerialID = 100;                                  //标识新增产品的系列ID
        int currentProductSerialID = 100;                           //当前新增产品的系列ID
        List<StartOrderBLL.STPhotoEdit> currentPhotos = new List<StartOrderBLL.STPhotoEdit>();  //当前显示使用的照片集合
        string OrilOrderPath = "";                                  //产品内照片的原始目录    
        List<StartOrderBLL.STPhotoEdit> NewPhotos = new List<StartOrderBLL.STPhotoEdit>();      //当前产品新增的照片
        List<StartOrderBLL.STPhotoEdit> ModifyPhotos = new List<StartOrderBLL.STPhotoEdit>();   //当前产品修改了的照片
        List<StartOrderBLL.STPhotoEdit> DelPhotos = new List<StartOrderBLL.STPhotoEdit>();      //当前产品删除了的照片
        int CurrentProductTypeCode = 1;                        //当前产品的类型码
        bool isNewProductCreating = false;                          //是否正在创建新产品(若新产品正在创建，其他操作不可用)
        bool isExistsEditProduct = false;                           //当前是否存在被编辑的产品
        string previousUnit = "";                                   //上一个使用的单位 
        List<StartOrderBLL.STProductTech> currentProductTechs;      //当前产品的流程
        List<StartOrderBLL.STProductTech> tempProductTechs = new List<StartOrderBLL.STProductTech>();   //保存已有产品的流程
        bool IsAddedScroll = false; //表示流程panel是否已加了scroll
        bool IsModifyProductType = false;                           //当前是否是要修改产品类型

        #region 加载原有产品进内存
        /// <summary>
        /// 加载原有产品进内存
        /// </summary>
        /// <param name="orderProductID"></param>
        private void AddProductIntoMemery(StartOrderBLL.ProductInfoEdit product)
        {
            try
            {
                List<StartOrderBLL.STPhotoEdit> ListPhoto;
                if (product.ProductTypeCode != (int)OrderInfoProductType.NeedDesignPrint)//除了需要指定尺寸的扩印产品
                {
                    ListPhoto = SOBLL.GetPhotoInOrderInfo(product.OrderProductId, UserType);
                    RasterCodecs.Startup();
                    RasterCodecs codecs = new RasterCodecs();
                    foreach (StartOrderBLL.STPhotoEdit photo in ListPhoto)
                    {
                        string fileFullPath = photo.PhotoFullPath;
                        FileInfo fileInfo = new FileInfo(fileFullPath);
                        //照片名称
                        photo.PhotoName = fileInfo.Name;
                        //照片数量

                        //照片大小
                        string sizeStr = "";
                        long fileSize = fileInfo.Length;
                        if (fileSize < 1024)
                        {
                            sizeStr = fileSize.ToString() + "B";
                        }
                        else if (fileSize < 1024 * 1024)
                        {
                            sizeStr = string.Format("{0:0.##}", (double)fileSize / 1024) + "K";
                        }
                        else if (fileSize < 1024 * 1024 * 1024)
                        {
                            sizeStr = string.Format("{0:0.##}", (double)fileSize / 1024 / 1024) + "M";
                        }
                        else
                        {
                            sizeStr = string.Format("{0:0.##}", (double)fileSize / 1024 / 1024 / 1024) + "G";
                        }
                        photo.PhotoSize = sizeStr;
                        CodecsImageInfo imgInfo = codecs.GetInformation(fileFullPath, true);
                        int resolution = imgInfo.XResolution;
                        int xPixel = imgInfo.Width;
                        int yPixel = imgInfo.Height;

                        //照片分辨率
                        photo.PhotoDPI = resolution;
                        float standardWidth = (float)xPixel / resolution;
                        float standardHeight = (float)yPixel / resolution;
                        //照片标准高宽，用于计算
                        photo.PhotoStandardHCompute = standardHeight;
                        photo.PhotoStandardWCompute = standardWidth;
                        //标准高宽，用于显示
                        string standardHW = string.Format("{0:0.####}", standardHeight) + "×" + string.Format("{0:0.####}", standardWidth);
                        photo.PhotoHWStandard = standardHW;
                        //标准面积
                        string standardArea = string.Format("{0:0.####}", standardWidth * standardHeight);
                        photo.PhotoAreaStandard = standardArea;
                        //照片像素高、宽
                        photo.PixHeight = yPixel;
                        photo.PixWidth = xPixel;
                    }
                    RasterCodecs.Shutdown();
                }
                else
                {
                    //从数据库获取照片的信息
                    ListPhoto = SOBLL.GetPhotoInOrderInfoXQ(product.OrderProductId);
                    RasterCodecs.Startup();
                    RasterCodecs codecs = new RasterCodecs();
                    foreach (StartOrderBLL.STPhotoEdit photo in ListPhoto)
                    {
                        string fileFullPath = photo.PhotoFullPath;
                        FileInfo fileInfo = new FileInfo(fileFullPath);
                        //照片名称
                        photo.PhotoName = fileInfo.Name;
                        //照片大小
                        string sizeStr = "";
                        long fileSize = fileInfo.Length;
                        if (fileSize < 1024)
                        {
                            sizeStr = fileSize.ToString() + "B";
                        }
                        else if (fileSize < 1024 * 1024)
                        {
                            sizeStr = string.Format("{0:0.##}", (double)fileSize / 1024) + "K";
                        }
                        else if (fileSize < 1024 * 1024 * 1024)
                        {
                            sizeStr = string.Format("{0:0.##}", (double)fileSize / 1024 / 1024) + "M";
                        }
                        else
                        {
                            sizeStr = string.Format("{0:0.##}", (double)fileSize / 1024 / 1024 / 1024) + "G";
                        }
                        photo.PhotoSize = sizeStr;
                        CodecsImageInfo imgInfo = codecs.GetInformation(fileFullPath, true);
                        int resolution = imgInfo.XResolution;
                        int xPixel = imgInfo.Width;
                        int yPixel = imgInfo.Height;

                        //照片分辨率
                        photo.PhotoDPI = resolution;

                        //照片标准高宽(因为已被修改过高宽，所以照片的高宽不再用其本身值,而是从数据库中读取)
                        float standardWidth = photo.PhotoStandardWCompute;
                        float standardHeight = photo.PhotoStandardHCompute;
                        //标准高宽，用于显示
                        string standardHW = string.Format("{0:0.####}", standardHeight) + "×" + string.Format("{0:0.####}", standardWidth);
                        photo.PhotoHWStandard = standardHW;
                        //标准面积
                        string standardArea = string.Format("{0:0.####}", standardWidth * standardHeight);
                        photo.PhotoAreaStandard = standardArea;
                        //照片像素高、宽
                        photo.PixHeight = yPixel;
                        photo.PixWidth = xPixel;
                    }
                    RasterCodecs.Shutdown();
                }
                product.Photos = ListPhoto;
                //加载打印机
                AddPrinter(product);
                //加载流程
                AddPrductTechs(product);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 加载产品流程
        /// <summary>
        /// 加载产品流程
        /// </summary>
        /// <param name="product"></param>
        public void AddPrductTechs(StartOrderBLL.ProductInfoEdit product)
        {
            //加载流程
            List<StartOrderBLL.STProductTech> FirstTechs = SOBLL.GetDefaultTechsOfProduct(product.ProductID);   //原产品默认的总流程
            foreach (StartOrderBLL.STProductTech stt in CommonProductTechBeforePrint)
            {
                StartOrderBLL.STProductTech sttTemp = FirstTechs.FirstOrDefault(p => p.TechID == stt.TechID);
                if (sttTemp == null)
                {
                    stt.IsNeed = false;
                    //stt.
                    FirstTechs.Add(stt);
                }
            }

            int currentTechId = 0;
            int tempCurrentTechId = SOBLL.GetCurrentTechId(product.OrderProductId); //获取当前节点的上一个节点
            int shopId = 0;                 //当前商户Id
            foreach (StartOrderBLL.STShop ss in ListShop)
            {
                if (ss.ShopName == cbShopName.Text)
                {
                    shopId = ss.ShopID;
                    break;
                }
            }
            //StartOrderBLL.STShop sshop = ListShop.FirstOrDefault(p=>p.);
            List<MODEL.CustomerManage.StartOrder.ShopTechUser> filterStu = Stu.FindAll(pt => pt.ShopId == shopId);
            if (IsModifyProductType == true && currentNewProductId != product.ProductID)        //修改产品类型
            {
                List<StartOrderBLL.STProductTech> SecondTechs = SOBLL.GetDefaultTechsOfProduct(currentNewProductId);//新产品默认的总流程
                currentTechId = tempCurrentTechId;
                //获取产品已分配的流程
                currentProductTechs = new List<StartOrderBLL.STProductTech>();
                product.DoingTechId = currentTechId;

                foreach (StartOrderBLL.STProductTech tech in FirstTechs)
                {
                    if (tech.TechID <= currentTechId)
                    {
                        currentProductTechs.Add(tech);
                    }
                }
                foreach (StartOrderBLL.STProductTech tech in SecondTechs)
                {
                    if (tech.TechID > currentTechId)
                    {
                        tech.IsNeed = true;
                        //新节点的默认员工

                        foreach (MODEL.CustomerManage.StartOrder.ShopTechUser s in filterStu)
                        {
                            if (s.TechId == tech.TechID)
                            {
                                tech.UserId = s.UserId;         //修改产品后，未完成部分流程全部改为默认员工
                                break;
                            }
                        }
                        currentProductTechs.Add(tech);
                    }
                }
            }
            else                                                                            //不用修改产品类型
            {
                currentProductTechs = FirstTechs;
            }
            //产品节点的全部默认员工
            foreach (StartOrderBLL.STProductTech tech in currentProductTechs)
            {
                foreach (MODEL.CustomerManage.StartOrder.ShopTechUser s in filterStu)
                {
                    if (tech.TechID == s.TechId)
                    {
                        tech.UserId = s.UserId;
                        break;
                    }
                }
                //默认的委外商
                if (currentTechId > 0)             //表示要换产品类型
                {
                    List<MODEL.CustomerManage.StartOrder.ProductOutShop> filterPo = new List<MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop>();
                    MODEL.CustomerManage.StartOrder.ProductOutShop nullPo = new MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop();
                    nullPo.ProductId = currentNewProductId;
                    nullPo.OutShopName = "(无)";
                    nullPo.OutShopId = 0;
                    filterPo.Add(nullPo);
                    if (tech.Techtype == (int)TechType.OutProduct)       //委外节点
                    {
                        if (tech.TechID > currentTechId)                                  //加载新产品的默认委外商
                        {
                            if (!Po.Exists(p => p.ProductId == currentNewProductId))
                            {
                                Po.AddRange(SOBLL.GetProductOutShop(currentNewProductId));
                            }
                            filterPo.AddRange(Po.FindAll(p => p.ProductId == currentNewProductId));
                        }
                        tech.Pos = filterPo;
                        foreach (MODEL.CustomerManage.StartOrder.ProductOutShop pp in filterPo)
                        {
                            if (pp.IsDefaultOutShop == true)
                            {
                                tech.OutShopId = pp.OutShopId;
                                break;
                            }
                        }
                    }
                }
            }
            tempProductTechs.Clear();
            //获取产品已分配的流程
            tempProductTechs = SOBLL.GetProductTechs(product.OrderProductId);
            foreach (StartOrderBLL.STProductTech tech in currentProductTechs)
            {
                if (currentTechId > 0 && tech.TechID > currentTechId)           //替换的后半流程，不用比较，全部Need
                    continue;
                if (tech.TechID <= tempCurrentTechId)
                {
                    tech.IsCompleted = true;                                    //已完成的节点不能再修改
                    tech.IsNessesary = true;                                    //已完成的流程不可修改
                }
                tech.IsNeed = false;
                foreach (StartOrderBLL.STProductTech tech2 in tempProductTechs)
                {
                    if (tech.TechID == tech2.TechID)
                    {
                        tech.UserId = tech2.UserId;                             //原来在该节点分配的员工
                        tech.IsNeed = true;
                        //原产品已分配的委外商
                        if (tech2.Techtype == (int)TechType.OutProduct && tech2.TechID > tempCurrentTechId)                   //如果委外节点已完成，就不需再执行任何操作
                        {
                            if (!Po.Exists(pt => pt.ProductId == tech2.ModelProductId))
                            {
                                Po.AddRange(SOBLL.GetProductOutShop(tech2.ModelProductId));
                            }
                            List<MODEL.CustomerManage.StartOrder.ProductOutShop> filterPo = new List<MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop>();
                            MODEL.CustomerManage.StartOrder.ProductOutShop nullPo = new MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop();
                            nullPo.OutShopId = 0;
                            nullPo.OutShopName = "(无)";
                            nullPo.ProductId = tech2.ModelProductId;
                            filterPo.Add(nullPo);
                            filterPo.AddRange(Po.FindAll(pt => pt.ProductId == tech2.ModelProductId));
                            tech.Pos = filterPo;
                            tech.OutShopId = SOBLL.GetOutShopIdByOrderProductId(product.OrderProductId);
                        }
                        break;
                    }
                }
            }
            product.techs = currentProductTechs;
        }
        #endregion

        #region 为产品加载打印机(包括新增产品和原有产品)
        /// <summary>
        /// 为产品加载打印机(包括新增产品和原有产品)
        /// </summary>
        /// <param name="product"></param>
        private void AddPrinter(StartOrderBLL.ProductInfoEdit product)
        {
            try
            {
                if (product.OrderProductId == 0)                //新增产品
                {
                    product.PrinterId = SOBLL.GetProductPrinter(product.ProductID);
                }
                else                                            //原有产品
                {
                    product.PrinterId = SOBLL.GetOrderProductPrinter(product.OrderProductId);
                }
                cbPrinter.SelectedValue = product.PrinterId;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 设置产品照片集合的大对象
        /// <summary>
        /// 设置产品照片集合的大对象
        /// </summary>
        /// <param name="photos">照片集合</param>
        private void SetPhotoAndThumbList(List<StartOrderBLL.STPhotoEdit> photos)
        {
            foreach (StartOrderBLL.STPhotoEdit p in photos)
            {
                PhotoListAndThumb pat = new PhotoListAndThumb();
                pat.Item = p;
                pat.ThumbIsAdded = false;
                PhotoAndThumbList.Add(pat);
            }
        }
        #endregion

        #region 是否可设计，设置可用与不可用，可见与不可见
        /// <summary>
        /// 是否可设计，设置可用与不可用，可见与不可见
        /// </summary>
        /// <param name="productTypeRemark">产品类型码</param>
        private void SetEnableAndDisable(int productTypeCode)
        {
            
            ceProductWithoutPhotoClick = false;//非鼠标点击

            switch (productTypeCode)
            {
                case (int)OrderInfoProductType.NeedDesignProduct:                           //1 需要设计的产品，开单时不可输入尺寸，可以输入P数
                    spinHeight.Enabled = false;
                    spinWidth.Enabled = false;
                    spinPageNum.Enabled = true;
                    //tsModifyPhotoHW.Visible = false;
                    ceProductWithoutPhoto.Checked = false;
                    break;
                case (int)OrderInfoProductType.NoNeedDesignProduct:                           //2 不需要设计的相册
                case (int)OrderInfoProductType.NoNeedDesignPrint:
                    spinHeight.Enabled = false;
                    spinWidth.Enabled = false;
                    spinPageNum.Enabled = false;
                    //tsModifyPhotoHW.Visible = false;
                    ceProductWithoutPhoto.Checked = false;

                    break;

                case (int)OrderInfoProductType.NoPhotoProduct:                           //5不含照片的类型
                    spinHeight.Enabled = false;
                    spinWidth.Enabled = false;
                    spinPageNum.Enabled = true;
                   // tsModifyPhotoHW.Visible = false;

                    ceProductWithoutPhoto.Checked = true;
                    break;
                case (int)OrderInfoProductType.NeedDesignPrint:               //需要设计的直出，开单时可输入尺寸，可输入P数
                    spinHeight.Enabled = true;
                    spinWidth.Enabled = true;
                    spinPageNum.Enabled = true;
                    //tsModifyPhotoHW.Visible = false;

                    ceProductWithoutPhoto.Checked = false;
                  
                    break;
                default:
                    spinHeight.Enabled = false;
                    spinWidth.Enabled = false;
                    spinPageNum.Enabled = false;
                   // tsModifyPhotoHW.Visible = false;
                    ceProductWithoutPhoto.Checked = false;


                    break;

            }
        }
        #endregion

        #region 显示产品内部信息
        /// <summary>
        /// 显示产品内部信息
        /// </summary>
        /// <param name="product"></param>
        private void DisPlayProductInfo(StartOrderBLL.ProductInfoEdit product)
        {
            try
            {
                SetEnableAndDisable(product.ProductTypeCode);     //设置可见于不可见，可用于不可用
                txtProductName.Text = product.ProductName;
                txtCtmName.Text = product.CtmName;
                spinProductNum.Text = product.ProductNum.ToString();
                string unit = cbUnit.Text;
                float h = product.Height;
                float w = product.Width;
                float hunit = 0;
                float wunit = 0;
                switch (unit)
                {
                    case "厘米(cm)":
                        hunit = h * (float)2.54;
                        wunit = w * (float)2.54;
                        break;
                    case "英寸(in)":
                        hunit = h;
                        wunit = w;
                        break;
                    case "米(m)":
                        hunit = h * (float)2.54 / 100;
                        wunit = w * (float)2.54 / 100;
                        break;
                    case "毫米(mm)":
                        hunit = h * (float)2.54 * 10;
                        wunit = w * (float)2.54 * 10;
                        break;
                }
                spinHeight.Tag = h;                             //真实高宽，用于计算
                spinWidth.Tag = w;
                spinHeight.Text = string.Format("{0:0.####}", hunit);
                spinWidth.Text = string.Format("{0:0.####}", wunit);
                foreach (StartOrderBLL.STPaperType ptype in ListPaperType)
                {
                    if (ptype.PaperTypeID == product.PaperTypeID)
                    {
                        cbPaperType.Text = ptype.PaperTypeName;
                        break;
                    }
                }
                foreach (StartOrderBLL.STPaperFace pface in ListPaperFace)
                {
                    if (pface.PaperFaceID == product.PaperFaceID)
                    {
                        cbPaperFace.Text = pface.PaperFaceName;
                        break;
                    }
                }
                spinPageNum.Text = product.PageNum.ToString();
                txtProductRemark.Text = product.ProductRemark;
                //设置当前显示的照片数据源
                foreach (StartOrderBLL.STPhotoEdit p in product.Photos)
                {
                    currentPhotos.Add(p);
                }
                ChangeDataSourceByUnit();                                       //按指定的单位显示
                //打印机
                cbPrinter.SelectedValue = product.PrinterId;

                gcProduct.DataSource = currentPhotos;
                gcProduct.RefreshDataSource();
                gvProduct.ClearSelection();
                foreach (StartOrderBLL.STProductTech stt in CommonProductTechBeforePrint)
                {
                    StartOrderBLL.STProductTech sttTemp = product.techs.FirstOrDefault(p => p.TechName == stt.TechName);
                    if (sttTemp == null)
                    {
                        stt.IsNeed = false;
                        //stt.
                        product.techs.Add(stt);
                    }
                }
                AddProductFlow(product.techs);                                  //加载产品的流程
                currentProductTechs = product.techs;
                SetPhotoProperty(false, product);                               //设置产品照片的属性
                ceProductWithoutPhotoClick = false;
                ceProductOutProductClick = false;
                if (product.ProductTypeCode == (int)OrderInfoProductType.NoPhotoProduct)
                {
                    ceProductWithoutPhoto.Checked = true;
                }
                if (product.OrderType == (int)OrderInfoType.OutReturnInfo)
                {
                    checkEditOutReturn.Checked = true;

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 设置当前产品照片的属性
        /// <summary>
        /// 设置当前产品照片的属性
        /// </summary>
        private void SetPhotoProperty(bool isNeedCC, StartOrderBLL.ProductInfoEdit product)
        {
            try
            {
                if (product.ProductTypeCode == (int)OrderInfoProductType.NoNeedDesignProduct)    //不需要设计的产品(判断照片尺寸是否与产品匹配,注意照片的宽应与产品宽的2倍匹配)
                {
                    float w = product.Width * 2;
                    float h = product.Height;
                    float maxW = w * (float)1.1;
                    float minW = w * (float)0.9;
                    float maxH = h * (float)1.1;
                    float minH = h * (float)0.9;
                    for (int i = 0; i < gvProduct.RowCount; i++)
                    {
                        StartOrderBLL.STPhotoEdit photo = gvProduct.GetRow(i) as StartOrderBLL.STPhotoEdit;
                        float ph = photo.PhotoStandardHCompute;
                        float pw = photo.PhotoStandardWCompute;
                        if (ph > maxH || ph < minH || pw > maxW || pw < minW)
                        {
                            photo.IsPiPei = false;
                        }
                        else
                        {
                            photo.IsPiPei = true;
                        }
                    }
                }
                else if (product.ProductTypeCode == (int)OrderInfoProductType.NeedDesignPrint && isNeedCC == true)   //需要指定尺寸的扩印(照片默认尺寸等于产品尺寸，单每张照片尺寸可单独修改)
                {
                    float h = product.Height;
                    float w = product.Width;
                    for (int i = 0; i < gvProduct.RowCount; i++)
                    {
                        StartOrderBLL.STPhotoEdit photo = gvProduct.GetRow(i) as StartOrderBLL.STPhotoEdit;
                        if (photo.PhotoStandardHCompute != h && photo.PhotoStandardWCompute != w)
                        {
                            //照片标准高宽，用于计算
                            photo.PhotoStandardHCompute = h;
                            photo.PhotoStandardWCompute = w;
                            //标准高宽，用于显示
                            string standardHW = string.Format("{0:0.####}", h) + "×" + string.Format("{0:0.####}", w);
                            photo.PhotoHWStandard = standardHW;
                            //标准面积
                            string standardArea = string.Format("{0:0.####}", h * w);
                            photo.PhotoAreaStandard = standardArea;
                            DisplayHWByUnit(photo);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 按单位设置产品的高宽
        /// <summary>
        /// 按单位设置产品的高
        /// </summary>
        /// <param name="product"></param>
        private void SetProductHW()
        {
            float rh = (float)(Convert.ToDouble(spinHeight.Tag));
            float rw = (float)(Convert.ToDouble(spinWidth.Tag));
            float h = 0;
            float w = 0;
            string unit = cbUnit.Text;
            switch (unit)
            {
                case "厘米(cm)":
                    h = rh * (float)2.54;
                    w = rw * (float)2.54;
                    break;
                case "英寸(in)":
                    h = rh;
                    w = rw;
                    break;
                case "米(m)":
                    h = rh * (float)2.54 / 100;
                    w = rw * (float)2.54 / 100;
                    break;
                case "毫米(mm)":
                    h = rh * (float)2.54 * 10;
                    w = rw * (float)2.54 * 10;
                    break;
            }
            spinHeight.Text = string.Format("{0:0.##}", h);
            spinWidth.Text = string.Format("{0:0.##}", w);
        }
        /// <summary>
        /// 设置宽
        /// </summary>
        private void SetProductW()
        {
            float w = (float)(Convert.ToDouble(spinWidth.Tag));
            string unit = cbUnit.Text;
            float w2 = 0;
            if (previousUnit == "厘米(cm)")
            {
                switch (unit)
                {
                    case "厘米(cm)":
                        w2 = w;
                        break;
                    case "英寸(in)":
                        w2 = w / (float)2.54;
                        break;
                    case "米(m)":
                        w2 = w / 100;
                        break;
                    case "毫米(mm)":
                        w2 = w * 10;
                        break;
                }
            }
            else if (previousUnit == "英寸(in)")
            {
                switch (unit)
                {
                    case "厘米(cm)":
                        w2 = w * (float)2.54;
                        break;
                    case "英寸(in)":
                        w2 = w;
                        break;
                    case "米(m)":
                        w2 = w * (float)2.54 / 100;
                        break;
                    case "毫米(mm)":
                        w2 = w * (float)2.54 * 10;
                        break;
                }
            }
            else if (previousUnit == "米(m)")
            {
                switch (unit)
                {
                    case "厘米(cm)":
                        w2 = w * 100;
                        break;
                    case "英寸(in)":
                        w2 = w * 100 / (float)2.54;
                        break;
                    case "米(m)":
                        w2 = w;
                        break;
                    case "毫米(mm)":
                        w2 = w * 1000;
                        break;
                }
            }
            else if (previousUnit == "毫米(mm)")
            {
                switch (unit)
                {
                    case "厘米(cm)":
                        w2 = w / 10;
                        break;
                    case "英寸(in)":
                        w2 = w / 10 / (float)2.54;
                        break;
                    case "米(m)":
                        w2 = w / 1000;
                        break;
                    case "毫米(mm)":
                        w2 = w;
                        break;
                }
            }
            spinWidth.Tag = w2;
            spinWidth.Text = string.Format("{0:0.##}", w2);
        }
        #endregion

        #region 修改高宽的事件
        //修改真实高
        private void spinHeight_Properties_Leave(object sender, EventArgs e)
        {
            try
            {
                float h = (float)Convert.ToDouble(spinHeight.Value);
                string unit = cbUnit.Text;
                float rh = 0;
                switch (unit)
                {
                    case "厘米(cm)":
                        rh = h / (float)2.54;
                        break;
                    case "英寸(in)":
                        rh = h;
                        break;
                    case "米(m)":
                        rh = h * 100 / (float)2.54;
                        break;
                    case "毫米(mm)":
                        rh = h / 10 / (float)2.54;
                        break;
                }
                spinHeight.Tag = rh;
                SetPhotoNumAndArea(CurrentProductTypeCode);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //修改真实宽
        private void spinWidth_Properties_Leave(object sender, EventArgs e)
        {
            try
            {
                float h = (float)Convert.ToDouble(spinWidth.Value);
                string unit = cbUnit.Text;
                float rh = 0;
                switch (unit)
                {
                    case "厘米(cm)":
                        rh = h / (float)2.54;
                        break;
                    case "英寸(in)":
                        rh = h;
                        break;
                    case "米(m)":
                        rh = h * 100 / (float)2.54;
                        break;
                    case "毫米(mm)":
                        rh = h / 10 / (float)2.54;
                        break;
                }
                spinWidth.Tag = rh;
                SetPhotoNumAndArea(CurrentProductTypeCode);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 照片的高宽、面积按不同的单位作不同的显示
        /// <summary>
        /// 根据不同单位，重新设置产品明细数据源的显示
        /// </summary>
        private void ChangeDataSourceByUnit()
        {
            try
            {
                for (int i = 0; i < currentPhotos.Count; i++)
                {
                    currentPhotos[i] = DisplayHWByUnit(currentPhotos[i]);
                }
                //gcProduct.RefreshDataSource();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 照片的高宽、面积按不同的单位作不同的显示
        /// </summary>
        /// <param name="photo"></param>
        private StartOrderBLL.STPhotoEdit DisplayHWByUnit(StartOrderBLL.STPhotoEdit photo)
        {
            float height = photo.PhotoStandardHCompute;
            float width = photo.PhotoStandardWCompute;
            string hw = "";
            string area = "";
            string unit = cbUnit.Text.Trim();
            switch (unit)
            {
                case "厘米(cm)":
                    hw = string.Format("{0:0.####}", height * 2.54) + "×" + string.Format("{0:0.####}", width * 2.54);
                    area = string.Format("{0:0.####}", height * width * 2.54 * 2.54);
                    break;
                case "英寸(in)":
                    hw = string.Format("{0:0.####}", height) + "×" + string.Format("{0:0.####}", width);
                    area = string.Format("{0:0.####}", height * width);
                    break;
                case "米(m)":
                    hw = string.Format("{0:0.####}", height * 2.54 * 0.01) + "×" + string.Format("{0:0.####}", width * 2.54 * 0.01);
                    area = string.Format("{0:0.####}", height * width * 2.54 * 2.54 * 0.01 * 0.01);
                    break;
                case "毫米(mm)":
                    hw = string.Format("{0:0.####}", height * 2.54 * 10) + "×" + string.Format("{0:0.####}", width * 2.54 * 10);
                    area = string.Format("{0:0.####}", height * width * 2.54 * 2.54 * 10 * 10);
                    break;
            }
            photo.Unit = unit;
            photo.PhotoHW = hw;
            photo.PhotoArea = area;
            return photo;
        }
        #endregion

        #region 显示的单位发生改变
        //显示的单位发生改变时
        private void cbUnit_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                //显示单位发生改变，不重新设置真实高宽
                string unitStr = cbUnit.Text;
                int index = unitStr.IndexOf("(");
                string partUnitStr = unitStr.Substring(0, index);
                DisplayByUnit(unitStr);                                                         //按单位显示
                ChangeDataSourceByUnit();                                                       //根据单位改变数据源
                gcProduct.RefreshDataSource();                                                  //
                SetPhotoNumAndArea(CurrentProductTypeCode);                                     //设置照片数量与面积
                //保存单位
                Properties.Settings.Default.PreviousUnit = cbUnit.Text;
                Properties.Settings.Default.Save();
                SetProductHW();                                                                 //设置照片的高宽
                //previousUnit = unitStr;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 照片列表与缩略图的大对象
        /// <summary>
        /// 照片列表与缩略图的大对象
        /// </summary>
        public class PhotoListAndThumb
        {
            public StartOrderBLL.STPhotoEdit Item { get; set; }   //照片列表
            public RasterImageListItem Thumb { get; set; }  //缩略图
            public bool ThumbIsAdded { get; set; }  //缩略图是否已加载
        }
        #endregion

        bool DisplayMode = false;                   //false列表 true缩略图

        #region "切换"按钮
        //"切换"按钮
        private void tsExchange_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (DisplayMode == false)       //当前是列表,点击后以缩略图显示
                {
                    RasterCodecs.Startup();
                    RasterCodecs codecs = new RasterCodecs();
                    if (PhotoAndThumbList == null || currentPhotos.Count == 0)
                    {
                        return;
                    }
                    foreach (PhotoListAndThumb pat in PhotoAndThumbList)
                    {
                        if (pat.ThumbIsAdded == false)      //还未加载缩略图
                        {
                            File.SetAttributes(pat.Item.PhotoFullPath, FileAttributes.Normal);
                            CodecsThumbnailOptions options = new CodecsThumbnailOptions();
                            options.Resample = true;
                            options.LoadStamp = true;
                            options.MaintainAspectRatio = true;
                            RasterImage img;
                            try
                            {
                                img = codecs.ReadThumbnail(pat.Item.PhotoFullPath, options, 1);
                            }
                            catch       //如果缩略图不存在，设置缩略图
                            {
                                RasterImage imgInfo = codecs.Load(pat.Item.PhotoFullPath);
                                Rectangle rec = RasterImage.CalculatePaintModeRectangle(imgInfo.Width, imgInfo.Height, new Rectangle(0, 0, 128, 128), RasterPaintSizeMode.FitAlways, RasterPaintAlignMode.Near, RasterPaintAlignMode.Near);
                                codecs.Options.Jpeg.Save.StampHeight = rec.Height;
                                codecs.Options.Jpeg.Save.StampWidth = rec.Width;
                                codecs.Options.Jpeg.Save.SaveWithStamp = true;
                                codecs.Options.Jpeg.Save.StampBitsPerPixel = 24;
                                codecs.Save(imgInfo, pat.Item.PhotoFullPath, RasterImageFormat.Jpeg, 0);
                                img = codecs.ReadThumbnail(pat.Item.PhotoFullPath, options, 1);
                            }

                            RasterImageListItem thumb = new RasterImageListItem(img, 1, pat.Item.PhotoName);
                            thumb.Tag = pat.Item.PhotoFullPath;
                            browser.Items.Add(thumb);
                            pat.Thumb = thumb;
                            pat.ThumbIsAdded = true;
                        }
                    }
                    codecs.Dispose();
                    RasterCodecs.Shutdown();
                    //同步
                    TongBu();
                    //移除列表对象,加载缩略图对象
                    spcProductDetail.Panel2.Controls.Clear();
                    spcProductDetail.Panel2.Controls.Add(browser);
                    //双击缩略图浏览大图
                    browser.DoubleClick += new EventHandler(browser_DoubleClick);
                }
                else        //当前是缩略图,点击后以列表显示
                {
                    //移除缩略图对象,加载列表对象
                    spcProductDetail.Panel2.Controls.Clear();
                    spcProductDetail.Panel2.Controls.Add(gcProduct);
                    //同步
                    TongBu();
                }
                DisplayMode = DisplayMode == true ? false : true;
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //双击缩略图显示大图
        void browser_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                RasterThumbnailBrowser b = sender as RasterThumbnailBrowser;
                string selectedPath = b.SelectedItems[0].Tag.ToString();
                //浏览大图
                List<string> photoPaths = new List<string>();
                int currentIndex = 0;
                foreach (RasterImageListItem item in b.Items)
                {
                    photoPaths.Add(item.Tag.ToString());
                    photoPaths.Add("");
                }
                for (int i = 0; 2 * i < photoPaths.Count; i++)
                {
                    if (selectedPath == photoPaths[2 * i])
                    {
                        currentIndex = 2 * i;
                        break;
                    }
                }
                ComControls.BigPicViewer bpv = new MINERP.ComControls.BigPicViewer();
                bpv.PhotoPaths = photoPaths;
                bpv.CurrentIndex = currentIndex / 2;
                bpv.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 缩略图与列表同步
        /// <summary>
        /// 缩略图与列表同步
        /// </summary>
        private void TongBu()
        {
            if (DisplayMode == false)          //当前显示的是列表
            {
                int[] indexes = gvProduct.GetSelectedRows();
                List<StartOrderBLL.STPhotoEdit> TBPhotos = new List<StartOrderBLL.STPhotoEdit>();
                foreach (int index in indexes)
                {
                    StartOrderBLL.STPhotoEdit photo = gvProduct.GetRow(index) as StartOrderBLL.STPhotoEdit;
                    TBPhotos.Add(photo);
                }
                foreach (PhotoListAndThumb pat in PhotoAndThumbList)
                {
                    bool isIn = false;
                    foreach (StartOrderBLL.STPhotoEdit photo in TBPhotos)
                    {
                        if (pat.Item == photo)
                        {
                            isIn = true;
                            pat.Thumb.Selected = true;
                            break;
                        }
                    }
                    if (isIn == false)
                    {
                        pat.Thumb.Selected = false;
                    }
                }
            }
            else                                //当前显示的是缩略图
            {
                RasterImageListItemCollection thumbs = browser.SelectedItems;
                gvProduct.ClearSelection();
                foreach (PhotoListAndThumb pat in PhotoAndThumbList)
                {
                    if (pat.Thumb.Selected == true)
                    {
                        StartOrderBLL.STPhotoEdit photo = pat.Item;
                        int srcIndex = currentPhotos.IndexOf(photo);            //在数据源中的索引
                        int index = gvProduct.GetRowHandle(srcIndex);
                        gvProduct.SelectRow(index);
                    }
                }
            }
        }
        #endregion

        #region 产品照片的拖曳操作
        private void gcProduct_DragEnter(object sender, DragEventArgs e)
        {
            try
            {
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    if (isExistsEditProduct == false)
                    {
                        return;
                    }
                    e.Effect = DragDropEffects.All;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void gcProduct_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                if (e.Data.GetDataPresent(DataFormats.FileDrop))
                {
                    object data = e.Data.GetData(DataFormats.FileDrop);
                    string[] paths = (string[])data;
                    if (paths.Length == 1)  //可能是目录或照片
                    {
                        if (Directory.Exists(paths[0]))
                        {
                            AddPhotoByDirectory(paths[0]);
                        }
                        else
                        {
                            AddPhotoByFiles(paths);
                        }
                    }
                    else                    //只可能是照片数组
                    {
                        AddPhotoByFiles(paths);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion
        //"打开目录"
        private void tsOpenDirectory_Click(object sender, EventArgs e)
        {
            try
            {
                if (isExistsEditProduct == false)
                {
                    MessageBox.Show("当前不存在选中的产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (DisplayMode == true)
                {
                    tsExchange_Click(sender, e);
                }
                string directoryPath = Properties.Settings.Default.StartOrderDirectory;
                if (Directory.Exists(directoryPath))
                {
                    folderBrowserDialog1.SelectedPath = directoryPath;
                }
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    string photoPath = folderBrowserDialog1.SelectedPath;
                    //执行加载照片操作
                    AddPhotoByDirectory(photoPath);

                    OrilOrderPath = photoPath;                                      //当前产品的原始路径
                    //保存本次使用的路径 
                    Properties.Settings.Default.StartOrderDirectory = photoPath;
                    Properties.Settings.Default.Save();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //"打开文件"
        private void tsOpenFile_Click(object sender, EventArgs e)
        {
            try
            {
                if (isExistsEditProduct == false)
                {
                    MessageBox.Show("当前不存在选中的产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (DisplayMode == true)
                {
                    tsExchange_Click(sender, e);
                }
                string directoryPath = Properties.Settings.Default.StartOrderFile;
                if (Directory.Exists(directoryPath))
                {
                    openFileDialog1.InitialDirectory = directoryPath;
                }
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    //执行加载照片操作
                    string[] filePaths = openFileDialog1.FileNames;
                    AddPhotoByFiles(filePaths);



                    //保存本次使用的照片所在的目录路径
                    FileInfo finfo = new FileInfo(filePaths[0]);
                    string photpPath = finfo.Directory.FullName;
                    OrilOrderPath = photpPath;                                //当前产品的原始路径      
                    Properties.Settings.Default.StartOrderFile = photpPath;
                    Properties.Settings.Default.Save();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #region 加载指定路径数组的一系列照片
        /// <summary>
        /// 加载指定路径数组的一系列照片
        /// </summary>
        /// <param name="files"></param>
        private void AddPhotoByFiles(string[] files)
        {
            if (files.Length > 0)
            {
                FileInfo fileInfo = new FileInfo(files[0]);
                OrilOrderPath = fileInfo.Directory.FullName;
            }
            //CheckIsNewProduct();        //判断是否是新加的产品，即是否还未添加照片信息

            RasterCodecs.Startup();
            RasterCodecs codecs = new RasterCodecs();
            foreach (string file in files)
            {
                AddSinglePhotoNoDesign(file, codecs);
            }
            codecs.Dispose();
            RasterCodecs.Shutdown();

            //设置新增照片的属性
            if (currentProductID != 0)                                      //表示是原有产品
            {
                foreach (StartOrderBLL.ProductInfoEdit product in ProductDataSource)
                {
                    if (product.OrderProductId == currentProductID)
                    {
                        SetPhotoProperty(true, product);
                        break;
                    }
                }
            }
            else                                                            //表示是新增产品
            {
                foreach (StartOrderBLL.ProductInfoEdit product in ProductDataSource)
                {
                    if (product.ProductSerialID == currentProductSerialID)
                    {
                        SetPhotoProperty(true, product);
                        break;
                    }
                }
            }
            gcProduct.RefreshDataSource();
            SetPhotoNumAndArea(CurrentProductTypeCode);                        //设置照片数量与面积
        }
        #endregion

        #region 加载一个目录下所有的照片
        /// <summary>
        /// 加载一个目录下所有的照片
        /// </summary>
        /// <param name="directory"></param>
        private void AddPhotoByDirectory(string directory)
        {
            OrilOrderPath = directory;
            ListAllPhotoPath.Clear();   //先将保存照片目录的集合清空
            GetAllPhotoPath(directory);
            //CheckIsNewProduct();        //判断是否是新加的产品，即是否还未添加照片信息


            RasterCodecs.Startup();
            RasterCodecs codecs = new RasterCodecs();
            foreach (string file in ListAllPhotoPath)
            {
                AddSinglePhotoNoDesign(file, codecs);
            }
            codecs.Dispose();
            RasterCodecs.Shutdown();

            //设置产品内照片的属性
            if (currentProductID != 0)
            {
                foreach (StartOrderBLL.ProductInfoEdit product in ProductDataSource)
                {
                    if (product.OrderProductId == currentProductID)
                    {
                        SetPhotoProperty(true, product);
                        break;
                    }
                }
            }
            else
            {
                foreach (StartOrderBLL.ProductInfoEdit product in ProductDataSource)
                {
                    if (product.ProductSerialID == currentProductSerialID)
                    {
                        SetPhotoProperty(true, product);
                        break;
                    }
                }
            }
            gcProduct.RefreshDataSource();
            SetPhotoNumAndArea(CurrentProductTypeCode);                        //设置照片数量与面积
        }
        #endregion

        #region 获取指定目录下所有的照片路径集合
        /// <summary>
        /// 获取指定目录下所有的照片路径集合
        /// </summary>
        /// <param name="directory">目录路径</param>
        private void GetAllPhotoPath(string directory)
        {
            string[] subDirectorys = Directory.GetDirectories(directory);
            foreach (string subDirectory in subDirectorys)
            {
                GetAllPhotoPath(subDirectory);
            }
            string pattern = "*.jpg|*.tif";
            string[] subFiles = GetFilesByPatterns(directory, pattern);
            foreach (string subFile in subFiles)
            {
                ListAllPhotoPath.Add(subFile);
            }
        }
        #endregion

        #region 加载单个照片(分为需要设计、不需要设计)
        /// <summary>
        /// 加载单个文件(需要设计)
        /// </summary>
        /// <param name="fileFullPath"></param>
        private void AddSingleFile(string fileFullPath)
        {
            foreach (StartOrderBLL.STPhotoEdit p in currentPhotos)        //判断照片是否已添加
            {
                if (fileFullPath == p.PhotoFullPath)
                    return;
            }
            StartOrderBLL.STPhotoEdit photo = AddPhotoCommon(fileFullPath);

            //保存进大对象
            PhotoListAndThumb pat = new PhotoListAndThumb();
            pat.Item = photo;
            pat.ThumbIsAdded = false;   //表示还未添加缩略图
            PhotoAndThumbList.Add(pat);

            //保存进当前新加照片集合 NewPhotos
            NewPhotos.Add(photo);
            currentPhotos.Add(photo);
        }

        /// <summary>
        /// 加载单个文件(不需要设计)
        /// </summary>
        /// <param name="fileFullPath"></param>
        /// <param name="codecs"></param>
        private void AddSinglePhotoNoDesign(string fileFullPath, RasterCodecs codecs)
        {
            try
            {
                foreach (StartOrderBLL.STPhotoEdit p in currentPhotos)    //判断照片是否已添加
                {
                    if (p.PhotoFullPath == fileFullPath)
                        return;
                }
                StartOrderBLL.STPhotoEdit photo = AddPhotoCommon(fileFullPath);
                CodecsImageInfo imgInfo = codecs.GetInformation(fileFullPath, true);
                int resolution = imgInfo.XResolution;
                int xPixel = imgInfo.Width;
                int yPixel = imgInfo.Height;

                float standardWidth = (float)xPixel / resolution;
                float standardHeight = (float)yPixel / resolution;
                //照片标准高宽，用于计算
                photo.PhotoStandardHCompute = standardHeight;
                photo.PhotoStandardWCompute = standardWidth;
                //标准高宽，用于显示
                string standardHW = string.Format("{0:0.####}", standardHeight) + "×" + string.Format("{0:0.####}", standardWidth);
                photo.PhotoHWStandard = standardHW;
                //标准面积
                string standardArea = string.Format("{0:0.####}", standardWidth * standardHeight);
                photo.PhotoAreaStandard = standardArea;
                //照片像素高、宽
                photo.PixHeight = yPixel;
                photo.PixWidth = xPixel;
                //高宽、面积需要按单位的不同作不同的显示
                photo = DisplayHWByUnit(photo);

                //照片的分辨率
                photo.PhotoDPI = resolution;

                //默认的照片数量1张
                photo.PhotoNum = 1;

                //保存进大对象
                PhotoListAndThumb pat = new PhotoListAndThumb();
                pat.Item = photo;
                pat.ThumbIsAdded = false;   //表示还未添加缩略图
                PhotoAndThumbList.Add(pat);

                //保存进当前新加照片集合 NewPhotos
                NewPhotos.Add(photo);
                currentPhotos.Add(photo);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 加载照片的中间操作
        /// <summary>
        /// 加载照片的中间操作
        /// </summary>
        /// <param name="fileFullPath"></param>
        /// <returns></returns>
        private StartOrderBLL.STPhotoEdit AddPhotoCommon(string fileFullPath)
        {
            StartOrderBLL.STPhotoEdit photo = new StartOrderBLL.STPhotoEdit();
            FileInfo fileInfo = new FileInfo(fileFullPath);
            //照片全路径
            photo.PhotoFullPath = fileInfo.FullName;
            //照片名称
            photo.PhotoName = fileInfo.Name;
            //照片大小
            string sizeStr = "";
            long fileSize = fileInfo.Length;
            if (fileSize < 1024)
            {
                sizeStr = fileSize.ToString() + "B";
            }
            else if (fileSize < 1024 * 1024)
            {
                sizeStr = string.Format("{0:0.##}", (double)fileSize / 1024) + "K";
            }
            else if (fileSize < 1024 * 1024 * 1024)
            {
                sizeStr = string.Format("{0:0.##}", (double)fileSize / 1024 / 1024) + "M";
            }
            else
            {
                sizeStr = string.Format("{0:0.##}", (double)fileSize / 1024 / 1024 / 1024) + "G";
            }
            photo.PhotoSize = sizeStr;
            //照片备注(默认为照片名)
            int index = fileInfo.Name.LastIndexOf(".");
            photo.PhotoRemark = fileInfo.Name.Substring(0, index);

            return photo;
        }
        #endregion

        #region 根据指定的筛选格式获取指定的照片
        /// <summary>
        /// 根据指定的筛选格式获取指定的照片
        /// </summary>
        /// <param name="directory"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        private string[] GetFilesByPatterns(string directory, string pattern)
        {
            string[] allFiles;
            List<string> listFiles = new List<string>();
            string[] ps = pattern.Split('|');
            foreach (string p in ps)
            {
                string[] pfiles = Directory.GetFiles(directory, p);
                foreach (string f in pfiles)
                    listFiles.Add(f);
            }
            allFiles = new string[listFiles.Count];
            for (int i = 0; i < listFiles.Count; i++)
            {
                allFiles[i] = listFiles[i];
            }
            return allFiles;
        }
        #endregion

        #region "删除"照片按钮
        //"删除"按钮
        private void tsDeletePhoto_Click(object sender, EventArgs e)
        {
            try
            {
                if (DisplayMode == false)                                   //当前按列表显示
                {
                    if (gvProduct.DataSource != null)
                    {
                        int[] delIndexes = gvProduct.GetSelectedRows();
                        DeletePhoto(delIndexes);                            //从列表删除
                    }
                }
                else
                {
                    RasterImageListItemCollection thumbs = browser.SelectedItems;
                    DeletePhotoThumb(thumbs);                               //从缩略图删除
                }
                gcProduct.RefreshDataSource();
                gvProduct.ClearSelection();
                SetPhotoNumAndArea(CurrentProductTypeCode);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 按Del键删除照片
        //列表
        private void gvProduct_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                int[] delIndexes = gvProduct.GetSelectedRows();
                if (e.KeyData == Keys.Delete && delIndexes.Length > 0)
                {

                    DeletePhoto(delIndexes);
                    gcProduct.RefreshDataSource();
                    gvProduct.ClearSelection();
                }
                //SetPhotoNumAndArea(currentProduct.IsNeedDesign);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        //缩略图
        void browser_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyData == Keys.Delete)
                {
                    RasterImageListItemCollection thumbs = browser.SelectedItems;
                    if (thumbs == null || thumbs.Count == 0)
                        return;
                    DeletePhotoThumb(thumbs);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 删除照片
        /// <summary>
        /// 删除照片(按列表删除)
        /// </summary>
        private void DeletePhoto(int[] delIndexes)
        {
            if (DialogResult.Yes == MessageBox.Show("确定要删除吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                //int temp = 0;
                //for (int i = 0; i < delIndexes.Length; i++)
                //{
                //    for (int j = i + 1; j < delIndexes.Length; j++)
                //    {
                //        if (delIndexes[i] < delIndexes[j])
                //        {
                //            temp = delIndexes[i];
                //            delIndexes[i] = delIndexes[j];
                //            delIndexes[j] = temp;
                //        }
                //    }
                //}
                //要删除的照片集合
                List<StartOrderBLL.STPhotoEdit> TempDelPhots = new List<StartOrderBLL.STPhotoEdit>();
                foreach (int index in delIndexes)
                {
                    StartOrderBLL.STPhotoEdit photo = gvProduct.GetRow(index) as StartOrderBLL.STPhotoEdit;
                    TempDelPhots.Add(photo);
                }
                foreach (StartOrderBLL.STPhotoEdit photo in TempDelPhots)
                {
                    DelPhotos.Add(photo);
                    currentPhotos.Remove(photo);                    //从列表删除
                    //从显示的大对象删除
                    foreach (PhotoListAndThumb pat in PhotoAndThumbList)
                    {
                        if (pat.Item == photo)
                        {
                            browser.Items.Remove(pat.Thumb);        //从缩略图删除
                            PhotoAndThumbList.Remove(pat);          //从大对象删除
                            break;
                        }
                    }
                }

            }
        }
        /// <summary>
        /// 删除照片(按缩略图删除)
        /// </summary>
        /// <param name="thums"></param>
        private void DeletePhotoThumb(RasterImageListItemCollection thumbs)
        {
            if (DialogResult.Yes == MessageBox.Show("确定要删除吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
            {
                foreach (RasterImageListItem thumb in thumbs)
                {
                    foreach (PhotoListAndThumb pat in PhotoAndThumbList)
                    {
                        if (pat.Thumb == thumb)
                        {
                            //保存删除记录
                            DelPhotos.Add(pat.Item);
                            //从内存中删除
                            browser.Items.Remove(thumb);
                            currentPhotos.Remove(pat.Item);
                            //从显示的大对象删除
                            PhotoAndThumbList.Remove(pat);
                            break;
                        }
                    }
                }
            }
        }
        #endregion

        //"确定"按钮  产品内部的修改操作
        private void tsAddProduct_Click(object sender, EventArgs e)
        {
            try
            {
                if (isExistsEditProduct == false)
                {
                    MessageBox.Show("当前不存在选中的产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (txtCtmName.Text == null || txtCtmName.Text.Length == 0)
                {
                    MessageBox.Show("客户名称不能为空!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (currentProductID != 0)                                 //表示是原有产品
                {
                    foreach (StartOrderBLL.ProductInfoEdit product in ProductDataSource)   //订单包的显示信息,保存信息一起更新,因为二者是同一个引用
                    {
                        if (currentProductID == product.OrderProductId)
                        {
                            bool r = ModifyDisplayProduct(product);         //r表示当前产品是否有照片
                            if (r == false)
                                return;
                            MessageBox.Show("产品修改信息已保存!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            ClearProductDetail();
                            gvProductList.FocusedRowHandle = -1;
                            gcProductList.RefreshDataSource();
                            isExistsEditProduct = false;                    //表示当前不存在正被编辑的产品
                        }
                    }
                }
                else                                                        //表示是新增产品
                {
                    foreach (StartOrderBLL.ProductInfoEdit product in ProductDataSource)    //订单包的显示信息,保存信息一起更新,因为二者是同一个引用
                    {
                        if (currentProductSerialID == product.ProductSerialID)
                        {
                            bool r = ModifyDisplayProduct(product);         //r表示当前产品是否有照片
                            if (r == false)
                                return;
                            product.ProductType = 1;                        //1表示新增
                            product.OrilOrderPath = OrilOrderPath;          //当前产品的原始路径
                            MessageBox.Show("新产品信息已保存!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            ClearProductDetail();
                            gcProductList.RefreshDataSource();
                            isNewProductCreating = false;                   //表示当前已无新产品正在添加,可进行其他操作
                            isExistsEditProduct = false;                    //表示当前不存在正被编辑的产品
                            gvProductList.FocusedRowHandle = -1;
                        }
                    }
                }
                txtCtmName.Enabled = true;
                IsModifyProductType = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #region 修改产品的显示信息、保存信息
        /// <summary>
        /// 修改产品的显示信息、保存信息
        /// </summary>
        /// <param name="product"></param>
        private bool ModifyDisplayProduct(StartOrderBLL.ProductInfoEdit product)
        {
            if (currentPhotos.Count == 0 && product.ProductTypeCode!=(int)OrderInfoProductType.NoPhotoProduct)
            {
                MessageBox.Show("产品的照片不能为空!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return false;
            }
            if (IsModifyProductType == true)
            {
                product.newProductId = currentNewProductId;
                product.ProductID = currentNewProductId;
            }
            product.CtmName = txtCtmName.Text.Trim();
            //string unit = cbUnit.Text;
            float rh = (float)(Convert.ToDouble(spinHeight.Tag));
            float rw = (float)Convert.ToDouble(spinWidth.Tag);
            product.Height = (float)Convert.ToDouble(string.Format("{0:0.##}", rh));
            product.ProductName = txtProductName.Text;
            product.ProductNum = Convert.ToInt16(spinProductNum.Text);
            product.ProductRemark = txtProductRemark.Text;
            product.ProductType = 2;                                        //2表示修改
            //product.techs = "";                                           //需要设置产品的流程
            product.Unit = cbUnit.Text;
            product.Width = (float)Convert.ToDouble(string.Format("{0:0.##}", rw));
            //foreach (StartOrderBLL.STPaperFace paperFace in ListPaperFace)
            //{
            //    if (paperFace.PaperFaceName == cbPaperFace.Text)
            //    {
            //        product.PaperFaceID = paperFace.PaperFaceID;
            //        product.PaperFaceName = paperFace.PaperFaceName;
            //        break;
            //    }
            //}
            //foreach (StartOrderBLL.STPaperType paperType in ListPaperType)
            //{
            //    if (paperType.PaperTypeName == cbPaperType.Text)
            //    {
            //        product.PaperTypeID = paperType.PaperTypeID;
            //        product.PaperTypeName = paperType.PaperTypeName;
            //        break;
            //    }
            //}
            //产品内的照片集合
            foreach (StartOrderBLL.STPhotoEdit photo in NewPhotos)              //新增的照片
            {
                photo.PhotoType = 1;                                            //1新增
                product.Photos.Add(photo);
            }
            foreach (StartOrderBLL.STPhotoEdit photo in DelPhotos)              //删除的照片
            {
                photo.PhotoType = 3;                                            //3删除
                if (photo.PhotoID != 0)                                         //表示不是新增的照片
                    DelPhotoIDS.Add(photo.PhotoID);
                product.Photos.Remove(photo);
            }
            if (product.ProductTypeCode==(int)OrderInfoProductType.NoPhotoProduct)
            {
                product.PageNum = Convert.ToInt32(spinPageNum.Text);
            }
            //产品的流程
            product.techs = currentProductTechs;
            //打印机
            product.PrinterId = Convert.ToInt32(cbPrinter.SelectedValue);
            return true;
        }
        #endregion

        #region 修改照片Remark
        //修改照片Remark
        private void gvProduct_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                StartOrderBLL.STPhotoEdit photo = gvProduct.GetRow(e.RowHandle) as StartOrderBLL.STPhotoEdit;
                photo.PhotoType = 2;                                                //2表示照片修改Remark
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        //产品份数发生改变
        private void spinProductNum_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                SetPhotoNumAndArea(CurrentProductTypeCode);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //Page数发生改变
        private void spinPageNum_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                SetPhotoNumAndArea(CurrentProductTypeCode);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //------------------------------------------------------------------
        //--------------新增产品--------------------------------------------
        //------------------------------------------------------------------
        #region 添加新产品的拖曳操作
        private void gcProductList_DragEnter(object sender, DragEventArgs e)
        {
            try
            {
                if (e.Data.GetDataPresent(DataFormats.StringFormat))
                {
                    e.Effect = DragDropEffects.All;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void gcProductList_DragOver(object sender, DragEventArgs e)
        {
            Point p = gcProductList.PointToClient(new Point(e.X, e.Y));
            DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = gvProductList.CalcHitInfo(p);
            if (info.InRow)
            {
                gvProductList.FocusedRowHandle = info.RowHandle;
            }
        }

        private void gcProductList_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                if (isNewProductCreating == false)
                {
                    if (IsModifyProductType == true)
                    {
                        MessageBox.Show("请先设置要修改类型的产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }
                    Point p = gcProductList.PointToClient(new Point(e.X, e.Y));
                    DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo info = gvProductList.CalcHitInfo(p);

                    if (info.InRow) //修改产品
                    {
                        if (e.Data.GetDataPresent(DataFormats.StringFormat))
                        {
                            //判断原产品的当前流程在新产品中是否存在，如果不存在，就不能修改
                            currentNewProductId = Convert.ToInt32(e.Data.GetData(DataFormats.StringFormat));
                            //StartOrderBLL.ProductInfo oldProduct = gvProductList.GetFocusedRow() as  StartOrderBLL.ProductInfo;
                            StartOrderBLL.ProductInfoEdit oldProduct = gvProductList.GetRow(info.RowHandle) as StartOrderBLL.ProductInfoEdit;

                            int oldProductId = oldProduct.ProductID;
                            bool IsExist = SOBLL.IsOldCurrentTechInNewProduct(oldProductId, currentNewProductId);
                            if (!IsExist)
                            {
                                MessageBox.Show("原产品的当前流程在新产品中不存在，不能替换!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                return;
                            }

                            //修改产品名称
                            string oldProductName = oldProduct.ProductName;
                            string newProductName = "";
                            float newHeight = 0;
                            float newWidth = 0;
                            foreach (StartOrderBLL.STProductDisplay product in ListProductDisplayShop)
                            {
                                if (currentNewProductId == product.ProductID)
                                {
                                    newProductName = product.ProductName;
                                    newHeight = (float)product.ProductH;
                                    newWidth = (float)product.ProductW;
                                    break;
                                }
                            }
                            int index = oldProductName.LastIndexOf("_");
                            newProductName = oldProductName.Substring(0, index + 1) + newProductName;
                            oldProduct.ProductName = newProductName;
                            oldProduct.Height = newHeight;
                            oldProduct.Width = newWidth;
                            gcProductList.RefreshDataSource();

                            IsModifyProductType = true;             //当前要修改产品类型
                            ModifyProductCommon();//打印机在本方法中加载
                        }
                    }
                    else            //新增产品
                    {
                        if (e.Data.GetDataPresent(DataFormats.StringFormat))
                        {
                            int pid = Convert.ToInt16(e.Data.GetData(DataFormats.StringFormat));
                            //执行清理操作
                            ClearProductDetail();
                            currentProductID = 0;                                       //表示不是原有的产品，而是新增的
                            gvProductList.ClearSelection();
                            isAddOldTech = false;                                        //表示正在加载新增产品的默认流程
                            currentProductTechs = SOBLL.GetDefaultTechsOfProduct(pid);
                            int shopId = 0;
                            foreach (StartOrderBLL.STShop s in ListShop)
                            {
                                if (s.ShopName == cbShopName.Text.Trim())
                                {
                                    shopId = s.ShopID;
                                    break;
                                }
                            }
                            List<MODEL.CustomerManage.StartOrder.ShopTechUser> filterStu = Stu.FindAll(pt => pt.ShopId == shopId);
                            //新产品节点的默认员工
                            foreach (StartOrderBLL.STProductTech tech in currentProductTechs)
                            {
                                foreach (MODEL.CustomerManage.StartOrder.ShopTechUser s in filterStu)
                                {
                                    if (tech.TechID == s.TechId)
                                    {
                                        tech.UserId = s.UserId;
                                        break;
                                    }
                                }
                                //默认委外商
                                if (tech.Techtype == (int)TechType.OutProduct)
                                {
                                    if (!Po.Exists(pt => pt.ProductId == pid))                  //当前产品的默认委外商集合还未加载    
                                    {
                                        Po.AddRange(SOBLL.GetProductOutShop(pid));
                                    }
                                    MODEL.CustomerManage.StartOrder.ProductOutShop nullPo = new MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop();
                                    nullPo.ProductId = pid;
                                    nullPo.OutShopName = "(无)";
                                    nullPo.OutShopId = 0;
                                    List<MODEL.CustomerManage.StartOrder.ProductOutShop> filterPo = new List<MINERP.MODEL.CustomerManage.StartOrder.ProductOutShop>();
                                    filterPo.Add(nullPo);
                                    filterPo.AddRange(Po.FindAll(pp => pp.ProductId == pid));
                                    tech.Pos = filterPo;
                                    foreach (MODEL.CustomerManage.StartOrder.ProductOutShop pp in filterPo)
                                    {
                                        if (pp.IsDefaultOutShop == true)            //默认的委外商
                                        {
                                            tech.OutShopId = pp.OutShopId;
                                            break;
                                        }
                                    }
                                }
                            }
                            foreach (StartOrderBLL.STProductTech stt in CommonProductTechBeforePrint)
                            {
                                StartOrderBLL.STProductTech sttTemp = currentProductTechs.FirstOrDefault(tn => tn.TechName == stt.TechName);
                                if (sttTemp == null)
                                {
                                    stt.IsNeed = false;
                                    //stt.
                                    currentProductTechs.Add(stt);
                                }
                            }
                            currentProductTechs.Sort(StartOrderBLL.CompareTech);        //排序
                            AddProductFlow(currentProductTechs);                        //添加产品的默认流程
                            AddNewProduct(pid);//打印机在本方法中加载
                            //客户名称可用
                            txtCtmName.Enabled = true;
                        }
                    }
                }
                else
                {
                    MessageBox.Show("请先设置新增产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 添加产品默认流程
        //产品默认流程
        private void AddProductFlow(List<StartOrderBLL.STProductTech> techs)
        {
            try
            {
                pProductFlow.Controls.Clear();
                techs.Sort(StartOrderBLL.CompareTech);
                int i = techs.Count;
                int j = i;
                foreach (StartOrderBLL.STProductTech pt in techs)
                {
                    if (j != i)
                    {
                        Label label = new Label();
                        label.Text = "->";
                        label.Dock = DockStyle.Left;
                        label.AutoSize = true;
                        pProductFlow.Controls.Add(label);
                    }
                    else
                        i--;
                    //节点委外商
                    if (pt.Techtype == (int)TechType.OutProduct)             //9表示委外节点
                    {
                        if (pt.Pos != null && pt.Pos.Count > 0)     //有委外商才需要加载
                        {
                            string outShopName = "(无委外)";
                            foreach (MODEL.CustomerManage.StartOrder.ProductOutShop pp in pt.Pos)
                            {
                                if (pp.OutShopId == pt.OutShopId)
                                {
                                    outShopName = "(" + pp.OutShopName + ")";
                                    pt.OutShopId = pp.OutShopId;
                                }
                            }
                            LinkLabel llOutShop = new LinkLabel();
                            llOutShop.Text = outShopName;
                            llOutShop.Tag = pt;
                            llOutShop.Dock = DockStyle.Left;
                            llOutShop.AutoSize = true;
                            llOutShop.Click += new EventHandler(llOutShop_Click);
                            pProductFlow.Controls.Add(llOutShop);
                        }
                    }
                    //节点的默认员工
                    string userName = "(无)";
                    if (pt.UserId != 0)
                    {
                        foreach (MODEL.CustomerManage.StartOrder.User u in AllUser)
                        {
                            if (pt.UserId == u.UserId)
                            {
                                userName = "(" + u.UserName + ")";
                                break;
                            }
                        }
                    }
                    LinkLabel llUser = new LinkLabel();
                    llUser.Text = userName;
                    llUser.Tag = pt;
                    llUser.Dock = DockStyle.Left;
                    llUser.AutoSize = true;
                    llUser.Click += new EventHandler(llUser_Click);
                    if (pt.IsCompleted)                             //如果节点已完成，员工不可修改
                        llUser.Enabled = false;
                    pProductFlow.Controls.Add(llUser);

                    CheckBox cb = new CheckBox();
                    cb.Text = pt.TechName;
                    cb.Dock = DockStyle.Left;
                    cb.AutoSize = true;
                    if (pt.IsNeed)
                    {
                        cb.Checked = true;

                    }
                    else
                    {
                        cb.Checked = false;
 
                    }
                    if (isAddOldTech == true && pt.IsNeed == false)     //如果是已有产品，且当前流程不需要时
                    {
                        cb.Checked = false;
                    }
                    if (isAddOldTech == false)
                        pt.IsNeed = true;
                    cb.CheckedChanged += new EventHandler(cb_CheckedChanged);
                    if (pt.IsNessesary == true)
                        cb.Enabled = false;
                    pProductFlow.Controls.Add(cb);
                }
                if (pProductFlow.HorizontalScroll.Visible == true) //需要水平滚动条时
                {
                    if (IsAddedScroll == false)
                    {
                        spcProductDetail.SplitterDistance += 15;
                        pProductFlow.Height += 15;
                        labelControl15.Location = new Point(labelControl15.Location.X, labelControl15.Location.Y + 15);
                        txtProductRemark.Location = new Point(txtProductRemark.Location.X, txtProductRemark.Location.Y + 15);
                        IsAddedScroll = true;
                    }
                }
                else
                {
                    if (IsAddedScroll == true)
                    {
                        spcProductDetail.SplitterDistance -= 15;
                        pProductFlow.Height -= 15;
                        labelControl15.Location = new Point(labelControl15.Location.X, labelControl15.Location.Y - 15);
                        txtProductRemark.Location = new Point(txtProductRemark.Location.X, txtProductRemark.Location.Y - 15);
                        IsAddedScroll = false;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //重设委外商
        void llOutShop_Click(object sender, EventArgs e)
        {
            try
            {
                LinkLabel llOutShop = (LinkLabel)sender;
                StartOrderBLL.STProductTech tech = (StartOrderBLL.STProductTech)llOutShop.Tag;

                FrmSetOutShop frm = new FrmSetOutShop();
                frm.frm = this;
                frm.Pos = tech.Pos;
                frm.OldOutShopId = tech.OutShopId;
                if (DialogResult.OK == frm.ShowDialog())
                {
                    llOutShop.Text = "(" + SelectedOutShopName + ")";
                    tech.OutShopId = SelectedOutShopId;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //重设节点默认员工
        void llUser_Click(object sender, EventArgs e)
        {
            try
            {
                LinkLabel lluser = (LinkLabel)sender;
                StartOrderBLL.STProductTech tech = (StartOrderBLL.STProductTech)lluser.Tag;

                List<MODEL.CustomerManage.StartOrder.User> filterUser = GetTechUser(tech.TechID);
                if (filterUser.Count == 1)
                    return;
                FrmSetUser frm = new FrmSetUser();
                frm.UserId = tech.UserId;
                frm.frm = this;
                frm.FilterUser = filterUser;
                if (DialogResult.OK == frm.ShowDialog())
                {
                    lluser.Text = "(" + SelectedUserName + ")";
                    tech.UserId = SelectedUserId;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 获取指定节点可用的员工列表
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        List<MODEL.CustomerManage.StartOrder.User> GetTechUser(int userId)
        {
            try
            {
                List<MODEL.CustomerManage.StartOrder.User> filterUser = new List<MINERP.MODEL.CustomerManage.StartOrder.User>();
                MODEL.CustomerManage.StartOrder.User nullUser = new MINERP.MODEL.CustomerManage.StartOrder.User();
                nullUser.UserId = 0;
                nullUser.UserName = "无";
                filterUser.Add(nullUser);
                filterUser.AddRange(AllUser.FindAll(p => p.TechId == userId));
                return filterUser;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //流程是否取消
        void cb_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                CheckBox cb = sender as CheckBox;
                if (cb != null)
                {
                    foreach (StartOrderBLL.STProductTech tech in currentProductTechs)
                    {
                        if (tech.TechName == cb.Text)
                        {
                            if (cb.Checked == true)
                            {
                                tech.IsNeed = true;
                            }
                            else
                            {
                                tech.IsNeed = false;
                            }
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 添加产品明细后，清除该产品明细
        /// <summary>
        /// 添加产品明细后，清除该产品明细
        /// </summary>
        private void ClearProductDetail()
        {
            txtProductName.Text = "";
            spinProductNum.Text = "1";
            spinWidth.Text = "1";
            spinHeight.Text = "1";
            spinPageNum.Text = "1";
            txtProductRemark.Text = "";
            lblPhotoNum.Text = "0";
            lblProductArea.Text = "0";
            if (DisplayMode == true)
            {
                spcProductDetail.Panel2.Controls.Clear();
                spcProductDetail.Panel2.Controls.Add(gcProduct);
                DisplayMode = false;
            }
            gcProduct.DataSource = null;
            currentPhotos.Clear();
            this.lblPhotoNum.Text = "0";
            this.lblProductArea.Text = "0";
            pProductFlow.Controls.Clear();
        }
        #endregion

        #region 添加新产品
        //添加新产品
        private void AddNewProduct(int productID)
        {
            foreach (StartOrderBLL.ProductInfo product in productListShop)
            {
                if (product.ProductID == productID)
                {
                    isNewProductCreating = true;                                                    //表示正在创建新产品,新产品正在创建时，不可执行其他操作
                    isExistsEditProduct = true;                                                     //表示当前存在正被编辑的产品
                    //设置产品头信息
                    SetProductTitle(product);
                    //添加新增产品进内存
                    //清除上个产品的信息
                    //清除表示当前产品照片变化的三个集合,及当前显示的产品照片集合
                    currentPhotos.Clear();
                    NewPhotos.Clear();
                    ModifyPhotos.Clear();
                    DelPhotos.Clear();
                    browser.Items.Clear();
                    PhotoAndThumbList.Clear();
                    gcProduct.DataSource = null;

                    StartOrderBLL.ProductInfoEdit newProduct = new StartOrderBLL.ProductInfoEdit();
                    newProduct.OrderProductId = 0;                                                  //表示是新增产品
                    newProduct.ProductID = product.ProductID;
                    newProduct.ProductSerialID = ProductSerialID;
                    currentProductSerialID = ProductSerialID;
                    newProduct.ProductName = product.ProductName;
                    newProduct.Photos = new List<StartOrderBLL.STPhotoEdit>();
                    newProduct.PageNum = product.PageNum;
                    newProduct.ProductNum = 1;                                                      //默认是1份
                    newProduct.CtmName = "";
                    CurrentProductTypeCode = product.ProductTypeCode;
                    currentProductID = 0;                                                           //表示是新增产品
                    currentProductSerialID = newProduct.ProductSerialID;                            //新增产品的系列号
                    newProduct.PaperTypeName = product.PaperTypeName;
                    newProduct.Status = (int)COM.OrderInfoStatus.Doing;
                    newProduct.techs = currentProductTechs;
                    foreach (StartOrderBLL.STPaperType ptype in ListPaperType)
                    {
                        if (product.PaperTypeName == ptype.PaperTypeName)
                        {
                            newProduct.PaperTypeID = ptype.PaperTypeID;
                            break;
                        }
                    }
                    newProduct.PaperFaceName = product.PaperFaceName;
                    foreach (StartOrderBLL.STPaperFace pface in ListPaperFace)
                    {
                        if (product.PaperFaceName == pface.PaperFaceName)
                        {
                            newProduct.PaperFaceID = pface.PaperFaceID;
                            break;
                        }
                    }
                    newProduct.Height = product.Height;
                    newProduct.Width = product.Width;
                    newProduct.ProductRemark = "";
                    newProduct.ProductTypeCode = product.ProductTypeCode;                       //产品类型码
                    CurrentProductTypeCode = newProduct.ProductTypeCode;
                    #region//设计产品规定尺寸
                    if (product.ProductTypeCode == (int)OrderInfoProductType.NeedDesignPrint || product.ProductTypeCode == (int)OrderInfoProductType.NeedDesignProduct)
                    {
                        FrmCheckSizeAndPage frm = new FrmCheckSizeAndPage(product);
                        frm.SizeUnit = "英寸(in)";
                        frm.Height = product.Height;
                        frm.Width = product.Width;
                        if (DialogResult.OK == frm.ShowDialog())
                        {
                            string unit = frm.SizeUnit;
                            double height = frm.Height;
                            double width = frm.Width;
                            switch (unit)
                            {
                                case "厘米(cm)":
                                    currentStyleProduct.ProductHeight = height / (float)2.54;
                                    currentStyleProduct.ProductWidth = width / (float)2.54;
                                    break;
                                case "英寸(in)":
                                    currentStyleProduct.ProductHeight = height;
                                    currentStyleProduct.ProductWidth = width;
                                    break;
                                case "米(m)":
                                    currentStyleProduct.ProductHeight = height * 100 / (float)2.54;
                                    currentStyleProduct.ProductWidth = width * 100 / (float)2.54;
                                    break;
                                case "毫米(mm)":
                                    currentStyleProduct.ProductHeight = height / 100 / (float)2.54;
                                    currentStyleProduct.ProductWidth = width / 100 / (float)2.54;
                                    break;
                            }

                        }
                        else
                        {
                            currentStyleProduct.ProductHeight = product.Height;
                            currentStyleProduct.ProductWidth = product.Width;
                        }
                    }
                    else
                    {
                        currentStyleProduct.ProductHeight = product.Height;
                        currentStyleProduct.ProductWidth = product.Width;
                    }
                    #endregion
                    //当前产品的基本样式
                    currentStyleProduct.ProductTypeCode = newProduct.ProductTypeCode;
                    //currentStyleProduct.ProductHeight = newProduct.Height;
                    //currentStyleProduct.ProductWidth = newProduct.Width;
                    currentStyleProduct.MaxHeight = currentStyleProduct.ProductHeight * 1.1;
                    currentStyleProduct.MinHeight = currentStyleProduct.ProductHeight * 0.9;
                    currentStyleProduct.MaxWidth = currentStyleProduct.ProductWidth * 2 * 1.1;
                    currentStyleProduct.MinWidth = currentStyleProduct.ProductWidth * 2 * 0.9;
                    //标识新增产品
                    ListProduct.Add(newProduct);                                                    //添加新增产品
                    ProductSerialID++;
                    //加载打印机
                    newProduct.PrinterId = SOBLL.GetProductPrinter(productID);
                    cbPrinter.SelectedValue = newProduct.PrinterId;
                    //加入上部产品列表
                    ProductDataSource.Add(newProduct);
                    int index = 0;
                    index = ProductDataSource.IndexOf(newProduct);

                    gcProductList.RefreshDataSource();
                    gvProductList.FocusedRowHandle = index;
                    gcProduct.DataSource = currentPhotos;
                    break;
                }
            }
        }
        #endregion

        #region 设置新产品的头信息
        /// <summary>
        /// 设置新产品的头信息
        /// </summary>
        /// <param name="productID"></param>
        private void SetProductTitle(StartOrderBLL.ProductInfo product)
        {
            txtProductName.Text = product.ProductName;
            float rh = product.Height;
            float rw = product.Width;
            float h = 0, w = 0;
            string unit = cbUnit.Text;
            switch (unit)
            {
                case "厘米(cm)":
                    h = rh * (float)2.54;
                    w = rw * (float)2.54;
                    break;
                case "英寸(in)":
                    h = rh;
                    w = rw;
                    break;
                case "米(m)":
                    h = rh * (float)2.54 / 100;
                    w = rw * (float)2.54 / 100;
                    break;
                case "毫米(mm)":
                    h = rh * (float)2.54 * 10;
                    w = rw * (float)2.54 * 10;
                    break;
            }
            spinHeight.Tag = rh;            //真实高宽
            spinWidth.Tag = rw;
            cbPaperType.Text = product.PaperTypeName;
            cbPaperFace.Text = product.PaperFaceName;
            spinPageNum.Text = product.PageNum.ToString();
            SetEnableAndDisable(product.ProductTypeCode);                   //设置可用与不可用，可见与不可见
            spinPageNum.Text = product.PageNum.ToString();
            spinHeight.Text = string.Format("{0:0.##}", h);
            spinWidth.Text = string.Format("{0:0.##}", w);
            //加载产品默认流程
            //AddProductFlow(productID);
        }
        #endregion

        #region "修改"按钮
        //"修改"按钮
        private void tsStartOrder_Click(object sender, EventArgs e)
        {
            try
            {
                string orderBagCode = txtOrderBagCode.Text;
                string orderName = txtOrderName.Text.Trim();
                if (IsModifyProductType == true)
                {
                    MessageBox.Show("请先设置要修改类型的产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (isNewProductCreating == true)
                {
                    MessageBox.Show("请先设置新增产品!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (orderName.Length == 0)
                {
                    MessageBox.Show("订单名称不能为空!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (cbPriority.Text.Length == 0)
                {
                    MessageBox.Show("请选择加急级别!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                string shopName = cbShopName.Text;
                if (shopName == "---请选择---")
                {
                    MessageBox.Show("请选择商户!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                ClearProductDetail();
                Cursor = Cursors.WaitCursor;
                int orderPriority = Convert.ToInt16(cbPriority.Text);
                int shopID = 0;

                DateTime orderTime = Convert.ToDateTime(dtOrderTime.Text);
                DateTime preCompleteTime = Convert.ToDateTime(dtPreCompleteTime.Text);

                string orderRemark = txtShopRequire.Text;
                foreach (StartOrderBLL.STShop s in ListShop)
                {
                    if (s.ShopName == shopName)
                    {
                        shopID = s.ShopID;
                        break;
                    }
                }
                //保存修改

                SOBLL.UpdateOrderBag(OrderBagID, ListProduct, DelProductIDs, DelPhotoIDS, orderBagCode, OrderBagID, orderName, orderPriority, shopID, shopName, orderTime, preCompleteTime, orderRemark, EditUserId);
                Cursor = Cursors.Default;
                MessageBox.Show("订单包修改成功!", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                /*
                //计算预估结余
                BillBLL billBll = new BillBLL();
                int result = billBll.UpdateBillInfo(OrderBagID);
                if (result == -1)
                {
                    MessageBox.Show("ID不正确", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else if (result == 0)
                {
                    MessageBox.Show("未找到此产品", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else if (result == 1)
                {
                    MessageBox.Show("此产品还未对该商户定价", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }*/

                this.Close();

                //ListProduct.Clear();                            //清空修改的信息
                //重新加载
                //AddOrderBagInfo();
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion
        //-------------------------------------------
        //--------------修改高宽操作-----------------
        //-------------------------------------------
        public float ModifyPhotoHeight;
        public float ModifyPhotoWidth;

        private void tsModifyPhotoHW_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvProduct.SelectedRowsCount == 0)
                {
                    MessageBox.Show("没有选中的照片", "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                //if (CurrentProductTypeCode == "3")
                //{
                //FrmModifyPhotoEditHW modifyPhoto = new FrmModifyPhotoEditHW();
                //modifyPhoto.EditOrder = this;
                //modifyPhoto.Unit = cbUnit.Text;
                //if (DialogResult.OK == modifyPhoto.ShowDialog())
                //{
                //    float realH = 0, realW = 0;
                //    switch (cbUnit.Text)
                //    {
                //        case "厘米(cm)":
                //            realH = ModifyPhotoHeight / (float)2.54;
                //            realW = ModifyPhotoWidth / (float)2.54;
                //            break;
                //        case "英寸(in)":
                //            realH = ModifyPhotoHeight;
                //            realW = ModifyPhotoWidth;
                //            break;
                //        case "米(m)":
                //            realH = ModifyPhotoHeight * 100 / (float)2.54;
                //            realW = ModifyPhotoWidth * 100 / (float)2.54;
                //            break;
                //        case "毫米(mm)":
                //            realH = ModifyPhotoHeight / 10 / (float)2.54;
                //            realW = ModifyPhotoWidth / 10 / (float)2.54;
                //            break;
                //    }
                if (DialogResult.OK == MessageBox.Show("确定修改选择的照片的尺寸", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                {
                    int[] indexes = gvProduct.GetSelectedRows();
                    foreach (int index in indexes)
                    {
                        StartOrderBLL.STPhotoEdit photo = gvProduct.GetRow(index) as StartOrderBLL.STPhotoEdit;
                        photo.PhotoType = 2;
                        //photo.PhotoStandardHCompute = realH;
                        //photo.PhotoStandardWCompute = realW;
                        photo.PhotoArea = string.Format("{0:0.####}", photo.PhotoStandardHCompute * photo.PhotoStandardWCompute);
                        photo.PhotoAreaStandard = string.Format("{0:0.####}", photo.PhotoStandardHCompute * photo.PhotoStandardWCompute);
                        photo.PhotoHW = string.Format("{0:0.####}", photo.PhotoStandardHCompute) + "×" + string.Format("{0:0.####}", photo.PhotoStandardWCompute);
                        photo.PhotoHWStandard = string.Format("{0:0.####}", photo.PhotoStandardHCompute) + "×" + string.Format("{0:0.####}", photo.PhotoStandardWCompute);
                        photo.IsModifySize = true;
                    }
                    gcProduct.RefreshDataSource();
                    SetPhotoNumAndArea(CurrentProductTypeCode);                                   //重新设置产品照片数量和面积
                    MessageBox.Show("照片尺寸修改成功！", "确认", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                //}
                //}
                //else
                //{
                //    int[] indexes = gvProduct.GetSelectedRows();
                //    foreach (int index in indexes)
                //    {
                //        StartOrderBLL.STPhotoEdit photo = gvProduct.GetRow(index) as StartOrderBLL.STPhotoEdit;
                //        photo.PhotoType = 2;
                //        //photo.IsModifySize = true;
                //    }
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void FrmEditOrder_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (UserType == 1)              //表示是普通编辑
            {
                Manage.EditOrderNum = 0;
            }
            else if (UserType == 2)         //表示是自动开单审核
            {
                CheckAutoOrder.editTimes = 1;
            }
        }

        //当产品是不需要指定高宽的相册类产品时，需要比较照片与产品是否匹配
        private void gvProduct_RowStyle(object sender, RowStyleEventArgs e)
        {
            try
            {
                BLL.CustomerManage.StartOrderBLL.STPhotoEdit photo = gvProduct.GetRow(e.RowHandle) as StartOrderBLL.STPhotoEdit;
                if (currentStyleProduct.ProductTypeCode == (int)OrderInfoProductType.NoNeedDesignProduct && photo != null)
                {
                    if ((photo.PhotoStandardHCompute <= currentStyleProduct.MaxHeight && photo.PhotoStandardHCompute >= currentStyleProduct.MinHeight) || (photo.PhotoStandardWCompute <= currentStyleProduct.MaxWidth && photo.PhotoStandardWCompute >= currentStyleProduct.MinWidth))
                    {

                    }
                    else
                    {
                        e.Appearance.BackColor = Color.Pink;
                        e.Appearance.BackColor2 = Color.Pink;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void txtZJM_EditValueChanged(object sender, EventArgs e)
        {
            if (txtZJM.Text == "")
                return;
            //if (xtraTabControl1.SelectedTabPage == xtraTabPage1)
            //{
            //    xtraTabControl1.SelectedTabPage = xtraTabPage2;
            //}
            string code = txtZJM.Text.ToUpper();
            SXList.Clear();
            foreach (StartOrderBLL.STProductDisplay pd in ListProductDisplayShop)
            {
                if (pd.ZJCode.Contains(code))
                {
                    SXList.Add(pd);
                }
            }
            var list = productListShop.Where(s => s.ZJCode.Contains(code));
            gcProductTemplate.DataSource = list;
            gcProductTemplate.RefreshDataSource();
            //AddProduct(SXList);
        }

        //修改照片数量与备注纸型纸面
        private void gvProduct_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {
                StartOrderBLL.STPhotoEdit photo = gvProduct.GetRow(e.RowHandle) as StartOrderBLL.STPhotoEdit;
                if (e.Column.FieldName == "PhotoNum")
                {
                    int pnum = 0;
                    try
                    {
                        pnum = Convert.ToInt32(e.Value);
                        photo.PhotoType = 2;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    photo.PhotoNum = pnum;
                }
                else if (e.Column.FieldName == "PhotoRemark")
                {
                    photo.PhotoRemark = e.Value.ToString();
                    photo.PhotoType = 2;
                }

                else if (e.Column.FieldName == "PaperTypeName")
                {
                    string photoTypeName = e.Value.ToString();
                    StartOrderBLL.STPaperType type = ListPaperType.FirstOrDefault(p => p.PaperTypeName == photoTypeName);
                    photo.PaperTypeID = type.PaperTypeID;
                    photo.PaperTypeName = type.PaperTypeName;
                    photo.PhotoType = 2;

                    //photo
                }
                else if (e.Column.FieldName == "PaperFaceName")
                {
                    string photoFaceName = e.Value.ToString();
                    StartOrderBLL.STPaperFace type = ListPaperFace.FirstOrDefault(p => p.PaperFaceName == photoFaceName);
                    photo.PaperFaceID = type.PaperFaceID;
                    photo.PaperFaceName = type.PaperFaceName;
                    photo.PhotoType = 2;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //刷新产品
        private void lblRefreshProduct_Click(object sender, EventArgs e)
        {
            try
            {
                //xtraTabControl1.SelectedTabPage = xtraTabPage1;
                //获取商户特有的产品集合
                string shopName = cbShopName.Text;
                int shopId = 0;
                foreach (StartOrderBLL.STShop s in ListShop)
                {
                    if (s.ShopName == shopName)
                    {
                        shopId = s.ShopID;
                        break;
                    }
                }

                //移除对Grid的引用
                //foreach (DevExpress.XtraNavBar.NavBarGroup g in bcProductCommon.Groups)
                //{
                //    if (g.ControlContainer != null && g.ControlContainer.Controls.Contains(gcProductCategoryShop))
                //    {
                //        g.ControlContainer.Controls.Remove(gcProductCategoryShop);
                //        break;
                //    }
                //}
                //bcProductCommon.Groups.Clear();
                if (shopId == 0)
                    return;
                productListShop = SOBLL.GetShopProductList(shopId);

                ListProductDisplayShop = new List<StartOrderBLL.STProductDisplay>();
                gcProductTemplate.DataSource = ListProductDisplayShop;
                gcProductTemplate.RefreshDataSource();
                //foreach (StartOrderBLL.ProductInfo s in productListShop)
                //{
                //    StartOrderBLL.STProductDisplay display = new StartOrderBLL.STProductDisplay();
                //    display.ProductID = s.ProductID;
                //    display.ProductName = s.ProductName;
                //    display.ProductCategoryID = s.ProductCategoryID;
                //    display.ProductCategoryName = s.ProductCategoryName;
                //    float rh = s.Height;
                //    float rw = s.Width;
                //    display.ProductHW = string.Format("{0:0.##}", rh) + "×" + string.Format("{0:0.##}", rw);
                //    display.ProductH = rh;
                //    display.ProductW = rw;
                //    display.ZJCode = s.ZJCode;
                //    ListProductDisplayShop.Add(display);
                //}

                //var groups = ListProductDisplayShop.GroupBy(p => p.ProductCategoryID);


                //foreach (var group in groups)
                //{
                //    foreach (var item in group)
                //    {
                //        DevExpress.XtraNavBar.NavBarGroup g = new DevExpress.XtraNavBar.NavBarGroup();

                //        g.Caption = item.ProductCategoryName;
                //        g.Tag = item.ProductCategoryID;
                //       //cProductCommon.Groups.Add(g);
                //        break;
                //    }
                //}
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        public int PhotoNum { get; set; }                       //照片数量(一次性设置多张照片的数量使用)
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvProduct.GetSelectedRows().Count() > 0)
                {
                    Cursor = Cursors.WaitCursor;
                    FrmPhotoNum frm = new FrmPhotoNum();
                    //frm.frm = this;
                    if (DialogResult.OK == frm.ShowDialog())
                    {
                        int[] indexes = gvProduct.GetSelectedRows();
                        foreach (int index in indexes)
                        {
                            StartOrderBLL.STPhotoEdit photo = gvProduct.GetRow(index) as StartOrderBLL.STPhotoEdit;
                            photo.PhotoNum = frm.ModifyNum;
                            photo.PhotoType = 2;//修改
                        }
                        gcProduct.RefreshDataSource();
                        Cursor = Cursors.Default;
                    }
                }
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void cbPaperType_SelectedIndexChanged(object sender, EventArgs e)
        {
            //ModifyProductCommon();
            //currentNewProductId
            MINERP.BLL.CustomerManage.StartOrderBLL.ProductInfoEdit product = ListProduct.FirstOrDefault(p => p.OrderProductId == currentProductID);
            string paperType = cbPaperType.Text;
            // ListPaperType
            StartOrderBLL.STPaperType stType = ListPaperType.FirstOrDefault(p => p.PaperTypeName == paperType);
            if (product != null)
            {
                product.PaperTypeID = stType.PaperTypeID;
                product.PaperTypeName = stType.PaperTypeName;
                gcProductList.RefreshDataSource();
                gcProduct.RefreshDataSource();
            }

        }

        private void cbPaperFace_SelectedIndexChanged(object sender, EventArgs e)
        {
            //currentNewProductId
            MINERP.BLL.CustomerManage.StartOrderBLL.ProductInfoEdit product = ListProduct.FirstOrDefault(p => p.OrderProductId == currentProductID);
            string paperFace = cbPaperFace.Text;
            // ListPaperType
            StartOrderBLL.STPaperFace stFace = ListPaperFace.FirstOrDefault(p => p.PaperFaceName == paperFace);
            if (product != null)
            {
                product.PaperFaceID = stFace.PaperFaceID;
                product.PaperFaceName = stFace.PaperFaceName;
                gcProductList.RefreshDataSource();
                gcProduct.RefreshDataSource();

            }

        }

        private void repositoryItemCheckedComboBoxEditCostType_Closed(object sender, DevExpress.XtraEditors.Controls.ClosedEventArgs e)
        {
            string str = "";
            foreach (DevExpress.XtraEditors.Controls.CheckedListBoxItem item in repositoryItemCheckedComboBoxEditCostType.Items)
            {
                if (item.CheckState.ToString() == "Checked")
                {
                    str += item.ToString() + ",";
                }

            }
            str = str.TrimEnd(',');
            ((MINERP.BLL.CustomerManage.StartOrderBLL.ProductInfoEdit)gvProductList.GetFocusedRow()).StringCostItems = str;
        }

        private void spinEditPhotoNum_EditValueChanged(object sender, EventArgs e)
        {
            int photoNum = Convert.ToInt32(spinEditPhotoNum.Text);
            List<StartOrderBLL.STPhotoEdit> listPhoto = ((StartOrderBLL.ProductInfoEdit)gvProductList.GetFocusedRow()).Photos;
            listPhoto.ForEach(p => p.PhotoNum = photoNum);
            gcProduct.RefreshDataSource();
        }

        private void ceProductWithoutPhoto_CheckedChanged(object sender, EventArgs e)
        {
            if (ceProductWithoutPhotoClick)//当鼠标点击时才激发一下事件
            {
                if (ceProductWithoutPhoto.Checked)
                {
                    MINERP.BLL.CustomerManage.StartOrderBLL.ProductInfoEdit currProduct = (StartOrderBLL.ProductInfoEdit)gvProductList.GetFocusedRow();
                    currProduct.ProductTypeCode = (int)OrderInfoProductType.NoPhotoProduct;
                }
                else
                {
                    MessageBox.Show("不能把不含照片的产品改成含照片的产品", "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    
                }
            }
        }

        private void ceProductWithoutPhoto_Click(object sender, EventArgs e)
        {
            ceProductWithoutPhotoClick = true;
        }

        private void checkEditOutReturn_CheckedChanged(object sender, EventArgs e)
        {
            ceProductOutProductClick = true;
        }

        private void ProductTemplate_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                downHitInfo = null;
                GridView view = sender as GridView;
                GridHitInfo hitInfo = view.CalcHitInfo(e.X, e.Y);
                if (ModifierKeys != Keys.None) return;
                if (e.Button == MouseButtons.Left && hitInfo.InRow && hitInfo.HitTest != GridHitTest.RowIndicator)
                    downHitInfo = hitInfo;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void ProductTemplate_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (e.Button == MouseButtons.Left && downHitInfo != null)
                {
                    System.Drawing.Size dragSize = SystemInformation.DragSize;
                    //Rectangle rec = new Rectangle(new Point(downHitInfo.HitPoint.X - dragSize.Width / 2, downHitInfo.HitPoint.Y - dragSize.Height / 2), dragSize);
                    //if (!rec.Contains(e.X, e.Y))
                    //{
                        int[] rows = view.GetSelectedRows();

                        if (rows.Length > 0)
                        {
                            if (!view.IsGroupRow(rows[0]))
                            {
                                StartOrderBLL.ProductInfo product = (StartOrderBLL.ProductInfo)view.GetRow(rows[0]);
                               // StartOrderBLL.STProductDisplay product = (StartOrderBLL.STProductDisplay)view.GetRow(rows[0]);
                                int pid = product.ProductID;
                                DataObject data = new DataObject();
                                data.SetData(DataFormats.StringFormat, pid.ToString());
                                DoDragDrop(data, DragDropEffects.All);
                                downHitInfo = null;
                            }
                        }
                    //}
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确认", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void gcProductTemplate_DragOver(object sender, DragEventArgs e)
        {
            //if (e.Data.GetDataPresent(typeof(DataFormats.Format)))
            //    e.Effect = DragDropEffects.Move;
            //else
            //    e.Effect = DragDropEffects.None; 
        }

    }
}
